简体   繁体   中英

option:selected not triggering .change()

I have a dropdown box that has a list of institutions in it. Now if I manually select an option, it works and I am able to grab the correct value.

However, I have a select rates button which uses JavaScript to pull up a rate sheet. You select a rate from that sheet and it will select an option from the dropdown for you (one that corresponds with the rate from the rate sheet). If I use this method, it doesn't trigger a .change() therefor I can't get a value for the selected option.

$('#id_financial_institution').change(function () {
          var value = $("#id_financial_institution option:selected").text()
          $("fi").text(value);
});

Any suggestions? I have tried .change() and .click() but nothing.

Once you are in the change function you don't have to do another search or selector because you already have the object you just have to find the selected option from it. So you can try this:

$('#id_financial_institution').change(function () {
          var value = $(this).find("option:selected").text();
          $("fi").text(value);
});

If the code still doesn't return you answer start to add alerts at each point to see where you are and what values you have and work your way from there?

Rather than .text() use .val()

$(function() {
    $('#id_financial_institution').change(function () {
          var value = $("#id_financial_institution option:selected").val()
         alert(value);
});

})

Here is a sample demo, without your html. I am just alerting the value.

DEMO

You're going about this all wrong. You already have the select element in this , all you need is the value of that select element.

$('#id_financial_institution').change(function () {
  var value = $(this).val();
  $('#fi').text(value); //i assume `fi` is an [id]
  //do more stuff
});

I went inside my AJAX call and got the value of the fields I needed there. For some reason, when using the AJAX call, it wouldn't fire the .change() on that particular field.

Thanks for all your input everyone.

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