html - Getting a drop down box value with javascript? - Stack Overflow

admin2025-04-20  0

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>

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>
Share Improve this question asked Nov 26, 2011 at 17:35 ritchritch 1,80814 gold badges38 silver badges66 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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);

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>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745081614a283893.html

最新回复(0)