如何获取下拉列表选中的值 jquery

如何获取下拉列表选中的值 jquery,第1张

分别使用javascript原生的方法和jquery方法

<select id="test" name="">

<option value="1">text1</option>

<option value="2">text2</option>

</select>

code:

一:javascript原生的方法

1:拿到select对象: var myselect=documentgetElementById("test");

2:拿到选中项的索引:var index=myselectselectedIndex ; // selectedIndex代表的是你所选中项的index

3:拿到选中项options的value: myselectoptions[index]value;

4:拿到选中项options的text: myselectoptions[index]text;

二:jquery方法(前提是已经加载了jquery库)

1:var options=$("#test option:selected"); //获取选中的项

2:alert(optionsval()); //拿到选中项的值

3:alert(optionstext()); //拿到选中项的文本

1html代码如下:

<html>

<head>

</head>

<body>

<form name="form1" id="form1">

Select your favorite fruit:

<select id="mySelect" name="mySelect">

<option value="11">Apple</option>

<option value="22" >Orange</option>

<option value="33">Pineapple</option>

<option value="44">Banana</option>

</select>

<br /><br />

<input type="button" onclick="getIndex()"

value="Alert index of selected option">

</form>

</body>

</html>

2javascript代码如下:

<script type="text/javascript">

function getIndex()

{

//从document对象中,获取select标签

var a=documentgetElementById("mySelect");

//select标签获取的值其实是一个数组--aoptions[]; 然后,选定项的下标是--aselectedIndex

var b=aoptions[aselectedIndex]value;

alert(b);

}

</script>

有时候我们需要在一个Select中传递两个有关联但不同的值,比如你的这个情况。这时候要利用到Option的另一个不常用属性Name,用Name来存储第二个值,然后在onchange事件中分别用thisoptions[thisselectedIndex]name来调用这个值。

全12333

全12321

全123123

在你的程序里,把

之间的内容作为name属性写出来,然后定义一个隐藏的input——optt,再定义好onchange事件,就可以同时获取到value和name两个值了。

获取选择项的文本和值:var i = documentgetElementById('s1')options[documentgetElementById('s1')selectedIndex]text;

documentgetElementById('s1')options[documentgetElementById('s1')selectedIndex]value;

使用2种方法给<p id=”p1”></p>添加其的文本内容“欢迎您!”

方法1:documentgetElementById('p1')innerHTML = i;

方法2:documentgetElementById('p1')appendChild(documentcreateTextNode(i));

可以使用:jQuery 属性 *** 作 - attr() 方法

attr() 方法的定义和用法

attr() 方法设置或返回被选元素的属性值。

根据该方法不同的参数,其工作方式也有所差异。

使用attr() 方法返回属性值

语法:$(selector)attr(attribute)。attribute

规定要获取其值的属性。

使用attr() 方法设置属性/值

语法$(selector)attr(attribute,value)。attribute规定属性的名称,value 规定属性的值。 

实例

// 改变图像的 width 属性:

$("button")click(function(){  $("img")attr("width","180");});

//获取select标签自定义属性 data-val的值

$("select")eq(0)attr("data-val")

以上就是关于如何获取下拉列表选中的值 jquery全部的内容,包括:如何获取下拉列表选中的值 jquery、如何利用javascript获取表单中select下拉列表中所选中项的值value、如何获取select的option的selected的value值等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9625542.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存