Anupam
Anupam

Reputation: 1841

jQuery for force triggering onChange of select dropdown

I want to trigger the onChange event of a select dropdown using jQuery. I have wired up the function with the onChange event by using : $(element2).change(populateRelatedDropdowns); It's working fine when I am manually changing the values of the select control. But when I want to trigger the onChange by using : $(entydd).trigger('change'); it simply doesn't work.

Please assist me. Thanks.

Code for wiring up the event with select dropdown :

var element2 = document.createElement("select");
$(element2).change(populateAttrsDropdowns);


function populateAttrsDropdowns() 
{
//does something
}

Upto this is smooth. Works when I change the dropdown values manually.

Now I have a requirement when I have manually set the option value for the dropdown and want the onChange even to be triggered. Code below(in a different function) :

for (i = 0; i < customArray.length; i++) 
{
    $('#btnAdd').trigger('click');
    var entydd = (i+1) + ".enty"; //this is the name of my dropdowns..there are a couple
    document.getElementById(entydd).value = customArray[i].custom_value;
    $(entydd).trigger('change');
}

Hope this extra code portion helps.

Upvotes: 1

Views: 7712

Answers (2)

The Alpha
The Alpha

Reputation: 146269

I think it should be

$('#'+entydd).trigger('change');

Upvotes: 3

mindandmedia
mindandmedia

Reputation: 6825

try to rewrite this:

for (i = 0; i < customArray.length; i++) 
{
    var mySelect = $((i+1) + ".enty");
    var myVal = customArray[i].custom_value;
    mySelect.val(myVal);
}

i haven't tested it, but that (setting the value on the select), just might trigger the change event, if you do it via jquery, as opposed to pure js.

and if it doesn't trigger the change, you can add a second call: myChanged(mySelect,myVal)

Upvotes: 0

Related Questions