MicTech
MicTech

Reputation: 45133

How I can detect change on Select, which is called from code?

I want to trigger .change() on select, if I change option in select element by code.

I take example from jQuery documentation and added my hook to link, which after click change selected option in select. And problem is if user click on that link, then change function doesn't react.

http://api.jquery.com/change/

$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();

$("#test").click(function () {
  $("select option:eq(2)").attr("selected", "selected")
});   

Upvotes: 0

Views: 594

Answers (1)

VeeWee
VeeWee

Reputation: 580

the change function only reacts to user actions. You can call: $('select').change(); manually:

$("#test").click(function () {
  $("select option:eq(2)").attr("selected", true);
  $('select').change();
}); 

You should use an ID, instead of the jquery selecter: 'select'. Just in case you use multiple selects on 1 page.

Upvotes: 1

Related Questions