Home  >  Article  >  Web Front-end  >  js gets the value selected by the select tag

js gets the value selected by the select tag

不言
不言Original
2018-03-31 14:15:221799browse

This article will share with you how to get the value selected by the select tag in js. Friends who need it can take a look

var obj = document.getElementById("testSelect"); //Positioning id

var index = obj.selectedIndex; // Selected index

var text = obj.options[index].text; // Selected text

var value = obj. options[index].value; // Selected value

Get the selected value in jQuery

The first way
$('#testSelect option:selected ').text();//Selected text

$('#testSelect option:selected') .val();//Selected value

$("#testSelect " ).get(0).selectedIndex;//Index

Second way
$("#tesetSelect").find("option:selected").text( );//Selected text
…….val();
…….get(0).selectedIndex;

-- ------------------------------------

如果select标签是有id属性的,如
<select id=xx>...
则用下述方法获取当前选项的值:
var v = xx.value;
或
var v = document.getElementById("xx").value;   //此方法兼容性好

如果select标签是有name属性的,如
<form name=form1>
<select name=xx>...
则用下述方法获取当前选项的值:
var v = form1.xx.value;
或
var v = document.getElementsByName("xx")[0].value;
如果同一页面含有多个name属性相同的标签,则上述[0]中的数字要改为相应的物理顺序号(从0起算)

如果select标签不含有任何可供定位的属性,如
<select>...
则用下述方法获取当前选项的值:
var v = document.getElementsByTagName("select")[0].value;
如果同一页面含有多个select标签,则上述[0]中的数字要改为相应的物理顺序号(从0起算)
----------------------------------------



对于以下select标签,获取当前选择的值得方式如下:

<select id="test" name="">
<option value="1">text1</option>
<option value="2">text2</option>
</select>
code:
一:javascript原生的方法
1:拿到select对象: var myselect=document.getElementById("test");
2:拿到选中项的索引:var index=myselect.selectedIndex ; // selectedIndex代表的是你所选中项的index
3:拿到选中项options的value: myselect.options[index].value;
4:拿到选中项options的text: myselect.options[index].text;

2: jquery method (provided that The jquery library has been loaded)

1:var options=$("#test option:selected"); //Get the selected item

2:alert(options.val()); //Get the value of the selected item

3:alert(options.text()); //Get the text of the selected item

The above is the detailed content of js gets the value selected by the select tag. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn