jQuery设置select的选中值

比如 <select id="testSelect"></select>

  1. 设置 value 为 test 的项选中
$("#testSelect").val("test");
  1. 设置 text 为 test 的项选中
$("#testSelect").find("option[text='test']").attr("selected", true);

example 1

<html>
<head>
    <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
    <script>
        function sel() {
            document.getElementById("show_index").innerHTML = $("#testSelect").get(0).selectedIndex;
            document.getElementById("show_all_text").innerHTML = $("#testSelect").text(); // 获取所有的文本
            document.getElementById("show_text").innerHTML = $("#testSelect option:selected").text(); // 获取选中的选项的文本
            document.getElementById("show_value").innerHTML = $("#testSelect").val();
            if ($("#op_3").is(":checked")) {
                document.getElementById("show_isSelected").innerHTML = "选中了";
            } else {
                document.getElementById("show_isSelected").innerHTML = "没选中";
            }
            $("#testSelect").aped("<option value="+op_5+">"+推荐系统+"<option>");
        }
		
		function set() {
			$("#testSelect").val(""); //设置value为空的项为选中状态
			sel();
		}
    </script>
</head>
<body>
	<button onclick="set()">测试</button>
    <select id="testSelect" onchange="sel()">
		<option id="op_0" value="">请选择</option>
        <option id="op_1" value="Deep Learning">深度学习</option>
        <option id="op_2" value="Machine Learning">机器学习</option>
        <option id="op_3" value="Data Mining">数据挖掘</option>
        <option id="op_4" value="Image Processing">图像处理</option>
    </select>
    <br>
    <hr><font color="red">选中的option索引:</font><p id="show_index"></p>
    <hr><font color="red">选中的option文本:</font><p id="show_text"></p>
    <hr><font color="red">选中的option的值:</font><p id="show_value"></p>
    <hr><font color="red">“数据挖掘”选项是否被选中:</font><p id="show_isSelected"></p>
    <hr><font color="red">所有选项的文本:</font><p id="show_all_text"></p>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清风醉雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值