开发者

Javascript and Forms getting value of selection option

How would I use Javascript to get the value of the options in this form selection?

I know I can use:

document.customerInfo.cardType.selectedIndex==4

but this wont work for me. I have over 30 and I really don't wan to code that much. Is there anyway I can just get the value of the option?

<form id="teamSelect"><select name="team">
    <option value="TEN">Tennessee</option>
    <option value="GB">Green Bay</option>
    </select>
    <input type="but开发者_如何学Cton" value="submit" onclick="games();"/>
    </form>


Add an ID to your select:

<select name="team" id="team">

Then do

document.getElementById("team").value

this will return TEN, GB, etc.


Get a reference to the form:

var form = document.getElementById('teamSelect');

or

var form = document.forms['teamSelect']

or if the form is given a name that is the same as its id:

var form = document.teamSelect;

Then iterate over its elements collection:

var elements = form.elements;
for (var i=0, iLen=elements.length; i<iLen; i++ ) {
  // elements[i] is a form control, get its value and
  // do whatever
}

Note that for select elements, the value is the value of the currently selected option.

While one option is supposed to be always selected (i.e. one should have the selected attribute so that it is the default selected option), in many cases that is omitted and the select can have no selected options. In this case, its selectedIndex property will be -1.

Also note that the value of a selected option is supposed to be the value of the value attribute and if it's missing, the value of the text property (the option's text). However IE gets this wrong and if there is no value attribute, returns an empty string. So to get the value of a select, you need to do:

function getSelectValue(select) {

  var idx = select.selectedIndex;

  // If one has been selected, return its value or text
  if (idx >=0) {
     return select.options[idx].value || select.options[idx].text

  // Otherwise none are selected - return empty string?
  } else {
     return '';
  }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜