Morgan Allen Morgan Allen - 1 month ago 12
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>" +
"</form>")

$('.location').append(myObj)


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
Volvo
. However, it was incorrect and it's actually a
Saab
. So, I change the option on the dropdown menu to
Saab
.

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

Answer

Add an event listener with jQuery:

$('.location').append(myObj)
$('select[name=cars]').change(function() {
    var selectedCar = $(this).val();
    // update DOM based on selectedCar
});