获取select下拉框的值
最近学习用到就总结起来,以便日后复习啦~~
案例:
1、新建web项目
2、下载jQuery
有两个版本的 jQuery 可供下载:
- Production version - 用于实际的网站中,已被精简和压缩。
- Development version - 用于测试和开发(未压缩,是可读的代码)
以上两个版本都可以从 jquery.com 中下载。
jQuery 库是一个 JavaScript 文件,等会放在页面相同目录下,就可以使用 HTML 的 <script> 标签引用它,如下:
<head>
<script src="jquery-3.4.1.js"></script>
</head>
放在不同目录直接在前面加路径就好。如:../jquery/jquery-3.4.1.js
最后直接看代码吧!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="jquery-3.4.1.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>小白网页</title>
<script>
function setalign(align){
var myselect=document.getElementById("selects");
var index=myselect.selectedIndex;// selectedIndex代表的是所选中项的index
alert("拿到select对象 : " + myselect);
alert("拿到选中项的索引: " + index);
alert("拿到选中项options的value:" + myselect.options[index].value);
alert("拿到选中项options的text:" + myselect.options[index].text);
//jquery方法(前提是已经加载了jquery库,方法文章里有)
//所谓jQuery操作“select”, 说的更确切一些是应该是jQuery控制 “option”
var options=$("#selects option:selected");//获取选中的项
alert("jquery方法拿到选中项的值: " + options.val());
alert("jquery方法拿到选中项的文本: " + options.text());
alert("jquery方法用name获取值: " + $('select[name=selects]').val());
//设置value=man/text='男'选中
$("#selects").val('man');
$("#selects").find("option[value = 'man']").attr("selected","selected");
$("#selects").find("option[text = '男']").attr("selected","selected");
/*
-------------- 扩展:
*/
/*
//获取第一个option的值
$('#selects option:first').val();
//最后一个option的值
$('#selects option:last').val();
//获取第二个option的值
$('#selects option:eq(1)').val();
//获取选中的值
$('#selects').val();
$('#selects option:selected').val();
//设置值为2的option为选中状态
$('#selects').attr('value','2');
//设置最后一个option为选中
$('#selects option:last').attr('selected','selected');
$("#selects").attr('value' , $('#selects option:last').val());
$("#selects").attr('value' , $('#selects option').eq($('#selects option').length - 1).val());
//获取select的长度
$('#selects option').length;
//添加一个option
$("#selects").append("<option value='n+1'>第N+1项</option>");
$("<option value='n+1'>第N+1项</option>").appendTo("#selects");
//添除选中项
$('#selects option:selected').remove();
//删除项选中(这里删除第一项)
$('#selects option:first').remove();
//指定值被删除
$('#selects option').each(function(){
if( $(this).val() == '5'){
$(this).remove();
}
});
$('#selects option[value=5]').remove();
//获取第一个Group的标签
$('#selects optgroup:eq(0)').attr('label');
//获取第二group下面第一个option的值
$('#selects optgroup:eq(1) : option:eq(0)').val();
*/
}
</script>
</head>
<body>
<div>
<select id="selects" onchange="setalign(this.value)" name="selects">
<option value="all">全部</option>
<option value="man">男</option>
<option value="women">女</option>
<option value="other">其他</option>
</select>
</div>
</body>
</html>