简体   繁体   中英

How to delete "selected" attribute from option using jquery

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. :(

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([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM