开发者

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>
    <开发者_JAVA技巧;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;


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.


Assign an ID to your select element:

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

And you can get the value like this:

document.getElementById('cars').value


You are missing an =. Change this

<form name "thecars">

To this

<form name="thecars">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜