ritch
ritch

Reputation: 1808

Getting a drop down box value with javascript?

I'm trying to get the value currently selected and I simply want to alert it.

I current have this:

<script type="text/javascript">

alert(forms.elements('sets').value);

</script>

HTML:

<form>
<select name="sets">
  <option value="1">1 Set</option>
  <option value="2">2 Sets</option>
  <option value="F">3 Sets</option>
</select>
</form>

Upvotes: 0

Views: 9978

Answers (2)

mplungjan
mplungjan

Reputation: 177930

Form without ID:

var val = document.forms[0].sets.value - first form on the page

Named form (form name="myForm") - will not validate in some doctypes:

var val = document.myForm.sets.value;

Form with ID (form id="myForm"):

var val = document.getElementById("myForm").sets.value;

Long version:

var sets = document.myForm.sets;
var val = sets.options[sets.selectedIndex].value;

Without the form - no ID on the select:

var val = document.getElementsByName("sets")[0].value; - first field with that name on the page

With ID on the select (select id="sets")

var val = document.getElementById("sets").value;


alert(val);

Upvotes: 3

Mouhong Lin
Mouhong Lin

Reputation: 4509

Try this:

<form>
<select name="sets">
  <option value="1">1 Set</option>
  <option value="2">2 Sets</option>
  <option value="F">3 Sets</option>
</select>
</form>

<script type="text/javascript">
    var select = document.getElementsByName('sets')[0];
    alert(select.value);
</script>

Upvotes: 0

Related Questions