简体   繁体   中英

Select-box control with jquery

I am using a selectbox:

<select name="priority" id="priority">
    <option value="4">Low</option>
    <option value="3" selected="selected">Normal</option>
    <option value="2">High</option>
    <option value="1">Emergency</option>
</select>

When user select "Emergency", then a confirmation box opens and if user confirm, then "Emergency" is selected. Otherwise "Normal" should be selected. For This, I am using jquery:

$(document).ready(function() {
    $('#priority').change(function(){
        if($(this).val()=='1'){
            if(confirm("Are you sure this is emergency?")){
                return true;
            }
            else{
                //here some code is needed to select "Normal".
            }
        }
    });
});

Now, How can I do that?

Since you're just returning in the confirmation case, you can shorten your logic down to this:

$(function() {
  $('#priority').change(function(){
    if($(this).val()=='1' && !confirm("Are you sure this is emergency?")){
      $(this).val('3');
    }
  });
});​

You can give it a try here .

else{
     $(this).find("option[value=3]").attr("selected","selected");
     //and trigger change after that if you need it
     $(this).change();
    }

The following code snippet should do what you are after - it selects the priority select element by ID and then sets the selected value to 3.

else 
{
    $('#priority').val(3);
}

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