最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to delete "selected" attribute from option using jquery - Stack Overflow

programmeradmin4浏览0评论

I want to remove the "selected" attribute from an option element when I uncheck this. I dont want to make value false or anything... I just want to delete this property. My code is like

$(function() {
  $("#deployselect").multiselect({
    click: function( event, ui ) {
      if(ui.checked==false){
        $("#deployselect option[value='"+ui.value+"']").removeAttr("selected");
      }
    }
  });
});

My generated HTML is like this

<option value="68" selected>A1</option>
<option value="49" selected>A2</option>
<option value="69" selected>A3</option>

so even i make "attr" or "prop" false it is not working. :(

I want to remove the "selected" attribute from an option element when I uncheck this. I dont want to make value false or anything... I just want to delete this property. My code is like

$(function() {
  $("#deployselect").multiselect({
    click: function( event, ui ) {
      if(ui.checked==false){
        $("#deployselect option[value='"+ui.value+"']").removeAttr("selected");
      }
    }
  });
});

My generated HTML is like this

<option value="68" selected>A1</option>
<option value="49" selected>A2</option>
<option value="69" selected>A3</option>

so even i make "attr" or "prop" false it is not working. :(

Share Improve this question edited Dec 13, 2012 at 11:09 Uzair asked Dec 13, 2012 at 10:41 UzairUzair 531 gold badge1 silver badge7 bronze badges 1
  • 4 What do you hope to achieve by removing that attribute? selected is a boolean property whose initial value is set based on the HTML attribute. – Alnitak Commented Dec 13, 2012 at 10:43
Add a ment  | 

2 Answers 2

Reset to default 14

If you want to de-select it, change this line:

$("#deployselect option[value='"+ui.value+"']").removeAttr("selected");

to

$("#deployselect option[value='"+ui.value+"']").prop("selected", false);

Live Example | Source

(Assuming jQuery 1.6 or later; for earlier versions, change prop to attr.)

Once the HTML has been parsed into the DOM, the option element has a property called selected which gets its initial value from the selected attribute in the HTML (defaulting to false). So once you're dealing with DOM elements, you're dealing with a boolean property, not an attribute anymore.

A simple option is to set selector value to empty so all checked list will uncheck

$("#deployselect").val([]);
发布评论

评论列表(0)

  1. 暂无评论