作为一个小白的开发人员,会经常用到单选和多选框的运用。

这篇文章主要介绍
1 单选框取值,监听值改变事件
2 如何选中和取消选中单选框

1 单选框取值,监听值改变事件
<input type="radio" name="colors" id="red" value="red">红色<br>
$('input[type=radio][name=colors]').on("change",function() {
alert(this.value);
});
实现效果如下图,可以监听到value中值的改变,通过this.value取到相应的值。

查看我们想要看的单选框是否被选中

2 如何选中和取消选中单选框
可以使用一下方法来取消和选中单选框
function check() {
// document.getElementById("red").checked = true
$("#red").prop('checked', true);
}
function uncheck() {
// document.getElementById("red").checked = false
$("#red").prop('checked', false);
}
整体代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>radio单选框测试</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<style>
body{
text-align: center;
margin: 100px;
line-height: 2;
</style>
</head>
<body>
<form>
你更喜欢哪种颜色?<br>
<input type="radio" name="colors" id="red" value="red">红色<br>
<input type="radio" name="colors" id="blue" value="blue">蓝色<br>
<input type="radio" name="colors" id="green" value="green">绿色
</form>
<button type="button" onclick="check()">选择 "红色"</button>
<button type="button" onclick="uncheck()">不选择 "红色"</button>
</body>
<script>
function check() {
// document.getElementById("red").checked = true
$("#red").prop('checked', true);
}
function uncheck() {
// document.getElementById("red").checked = false
$("#red").prop('checked', false);
}
$('input[type=radio][name=colors]').on("change",function() {
alert(this.value);
});
</script>
</html>

想看电影关注我的公众号:电影资源集(支持输入电影名称自动回复了)
喜欢就点个👍吧
网友评论