简体   繁体   中英

jQuery - disabled first option on select click, but keep box open?

I have an address select dropdown, with a default "Select your address" . When the user clicks the select box, I want the default option to be disabled, but for the dropdown to stay open with nothing selected so the user can choose from the list.

Current behaviour is the second option being auto-selected and the dropdown closing.

let addressClickCount;

if ($("#js-address-select option").length > 1) {
  $("#js-address-select").html($("#js-address-select option")
                         .sort(function (a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
      }))

   const blankAddress = new Option("-- SELECT YOUR ADDRESS --")

   $("#js-address-select").prepend(blankAddress)

   $("#js-address-select").click(function() {
     if (addressClickCount === 0) {
       $(blankAddress).attr('disabled','disabled')
       $(blankAddress).prop("selected", false)
       $("#js-address-select option[value='*']").attr('selected', false)
     }

     addressClickCount++
   })
 }

 $("#js-address-select").prop("selectedIndex", 0);
}

All you should really need to do is disable the first option on click.

 const blankAddress = new Option("-- SELECT YOUR ADDRESS --") $("#js-address-select").prepend(blankAddress) $("#js-address-select option:eq(0)").prop("selected",true); $('#js-address-select').click(function(){ $(this).find('option:eq(0)').prop('disabled',true) }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="js-address-select"> <option>Address A</option> <option>Address B</option> <option>Address C</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