首页 > Web开发 > 详细

在js中如何使用单选框

时间:2020-03-04 19:26:58      阅读:92      评论:0      收藏:0      [点我收藏+]

方法一

先用getElementsByName筛选出需要的单选框元素(type="radio"),循环检查radio.checked是否为true
测试用的是菜鸟的网页测试因为偶然学到这里

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function displayResult(){
    var colors=document.getElementsByName("colors");
    for(i=0;i<colors.length;i++){
        if(colors[i].checked){
            alert(colors[i].id);
        }
    }
}
</script>
</head>
<body>

<form>
你更喜欢哪种颜色?<br>
<input type="radio" name="colors" id="red">红色<br>
<input type="radio" name="colors" id="blue">蓝色<br>
<input type="radio" name="colors" id="green">绿色
</form>
<button type="button" onclick="displayResult()">显示 input 内容</button>

</body>
</html>
技术分享图片

方法二

直接在radio元素中添加onclick="getValue(this.value)"
然后覆写这个方法实现功能

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function getValue(id){
    alert(id);
}
</script>
</head>
<body>

<form>
你更喜欢哪种颜色?<br>
<input type="radio" name="colors" id="red" onclick="getValue(this.id)">红色<br>
<input type="radio" name="colors" id="blue" onclick="getValue(this.id)">蓝色<br>
<input type="radio" name="colors" id="green" onclick="getValue(this.id)">绿色
</form>


</body>
</html>
技术分享图片

很郁闷,发出了信息,然后才会改变单选框,不过不跳出信息大概不会有这个问题,直接改变就可以了。

在js中如何使用单选框

原文:https://www.cnblogs.com/Stratford-International/p/12411246.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!