简体   繁体   中英

Event handling of select change in jQuery doesn't return the current selectedIndex

I'm trying to do the following: Show a drop down with jquery, which has a structure like:

  • Add element
  • Element 1
  • Element 2

Now, I would like to have the following behavior: The user looks at "Add element" and clicks it. He then selects one of the elements, some function gets called and then the drop down selection goes back to the title "Add element".

This is what I hoped would work:

$('#elementselect').change(function(e) {            
  selectedIndex = $("#gadgetselect").attr('selectedIndex');

  if (selectedIndex != 0) {
    var selectmenu = document.getElementById("elementselect");
    chosenoption = selectmenu.options[selectedIndex];
    load_element(chosenoption.value);
    $("#elementselect").attr('selectedIndex', 0);
  }
});

If Element 1 is selected, .change is called and the load_element function is called. After setting the selectedIndex back to 0, the .change function is called again, however selectedIndex is still 1 there. So the load_element function gets called twice... Any ideas?

Access the selectedIndex property of the <select> element directly. Also, use the var keyword to declare a local variable, unless you really intended selectedIndex to be accessible outside the event handler function.

var selectedIndex = $("#gadgetselect")[0].selectedIndex;
// ...
this.selectedIndex = 0;

You could use jQuery's prop() method if you really must, but there's no benefit whatsoever in doing so in this case.

var selectedIndex = $("#gadgetselect").prop("selectedIndex");
// ...
$(this).prop("selectedIndex", 0);

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