简体   繁体   中英

Remove selected option if disabled

As the title suggests, I would like to have the selected option cleared when disabled.

For instance, if a user selects "Angelina Jolie" and clicks the checkbox "Exclude Name", Angelina Jolie should be deselected and disabled and the select should show "Select Name" instead.

JSFiddle Demo: https://jsfiddle.net/c26teqjb/

HTML

<div class="">
  <label class="checkbox">
    <input type="checkbox" name="optradio" id="filtri">
    <span class="checkboxtext">Exclude Name</span>
  </label>
</div>
<select id="filtrin">
  <option selected="">Select Name</option>
  <option>Kleenco</option>
  <option>James Franco</option>
  <option>Angelina Jolie</option>
  <option>Jack Black</option>
</select>

JS:

$(document).ready(function () {
  $("#filtri").click(function () {
    $('#filtrin').attr("disabled", $(this).is(":checked"));
  });
});

you can reset to first index like below,

$(document).ready(function () {
  $("#filtri").click(function () {
    $("#filtrin").prop('selectedIndex', 0);
    $('#filtrin').attr("disabled", $(this).is(":checked"));
  });
});

check this

 $(document).ready(function () { $("#filtri").click(function () { $('#filtrin').attr("disabled", $(this).is(":checked")); var x = $('#filtrin').val(); $('#filtrin option').each(function(){ console.log($(this).text()); if($(this).text() == x && $(this).text() !="Select Name"){ $(this).remove(); } }); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class=""> <label class="checkbox"> <input type="checkbox" name="optradio" id="filtri"> <span class="checkboxtext">Exclude Name</span> </label> </div> <select id="filtrin"> <option selected="">Select Name</option> <option>Kleenco</option> <option>James Franco</option> <option>Angelina Jolie</option> <option>Jack Black</option> </select> 

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