Morgan Allen Morgan Allen - 1 year ago 77
HTML Question

Change the DOM based on a drop down menu

I'm trying to do something hackerish and not sure how to go about doing it.

I'm injecting a dropdown menu onto a web page

var myObj = $("<form action='action_page.php'>" +
"<select name='cars'>" +
"<option value='volvo'>Volvo</option>" +
"<option value='saab'>Saab</option>" +
"<option value='fiat'>Fiat</option>" +
"<option value='audi'>Audi</option>" +
"</select>" +


I'll be setting the initial option value when the page is loaded based off of some other data.

So for example, I'm looking through car profiles and some backend service guesses the type of car.

When the page is loaded, the dropdown value is set to
. However, it was incorrect and it's actually a
. So, I change the option on the dropdown menu to

Is there a way to reflect this change in the DOM without having to hit a submit button?

Answer Source

Add an event listener with jQuery:

$('select[name=cars]').change(function() {
    var selectedCar = $(this).val();
    // update DOM based on selectedCar
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download