Ramar
Ramar

Reputation: 1564

javascript event not getting triggered

I have a dropdown for number of travelers.

When I change the value (say select 2), it displays some more dropdowns (in this case 2 dropdowns) for entering the age of travelers.

This is existing functionality. Now I have created another dropdown, here I have written an onChange function that sets the value of travelers:

document.getElementById("travellers").value="1";

I want the additional dropdowns for the age to appear on their own which does not happen.

How can I effect this to happen using jQuery/JavaScript?

Upvotes: 0

Views: 144

Answers (1)

Satpal
Satpal

Reputation: 133403

When you modifies value programatically event will not fire. You need to trigger event.

Using vanilla JS

var select = document.getElementById("travellers");
//fire the event
if("createEvent" in document) { //NON IE browsers
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    select.dispatchEvent(evt);
} else { //IE
    var evt = document.createEventObject();
    select.fireEvent("onchange", evt);
}

As you have tagged your question with jQuery you can use .trigger()

$("#travellers").trigger("change");

Upvotes: 2

Related Questions