Mike
Mike

Reputation: 3

Getting a select's value with javascript

I have the following condensed form

<form name="thecars">
<select name="cars">
    <option value="mustang">Mustang</option>
    <option value="pinto">Pinto</option>
    <option value="pinto">Chevelle</option>
    <option value="pinto">Other</option>
</select>
</form>

I am trying to get the value of the selected car by the following but it is not working

selectedCar = document.forms["thecars"].elements["cars"].options[thecars.cars.options.selectedIndex].value;

Upvotes: 0

Views: 143

Answers (3)

Shadow Wizard
Shadow Wizard

Reputation: 66399

Correct code would be:

var oForm = document.forms["thecars"];
var oDDL = oForm.elements["cars"];
var selectedCar = oDDL.value;

You can't get reference to the form by just using its name.

Upvotes: 3

Ben Lee
Ben Lee

Reputation: 53309

You are missing an =. Change this

<form name "thecars">

To this

<form name="thecars">

Upvotes: 0

casablanca
casablanca

Reputation: 70691

Assign an ID to your select element:

<select name="cars" id="cars">

And you can get the value like this:

document.getElementById('cars').value

Upvotes: 2

Related Questions