Morgan Allen Morgan Allen - 2 months ago 18
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?


Add an event listener with jQuery:

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