html单选框怎么用js实现选中

html单选框怎么用js实现选中,第1张

设置radio的checked属性为ture即为选中。

<input type="radio" id="radioId" value="1" >

选中单选框JS代码:

var target = document.getElementById("radioId")

target.checked = true

附完整代码:

<!DOCTYPE html>

<!--STATUS OK-->

<html>

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

<meta http-equiv="content-type" content="text/htmlcharset=gbk" />

<meta property="wb:webmaster" content="3aababe5ed22e23c" />

<meta name="referrer" content="always" />

<title>demo</title>

</head>

<body>

<input type="radio" value="radio1" id="radio1" name="radio"/><label for="radio1">RADIO 1</label>

<input type="radio" value="radio2" id="radio2" name="radio"/><label for="radio2">RADIO 2</label>

<input type="radio" value="radio3" id="radio3" name="radio"/><label for="radio3">RADIO 3</label>

<input type="radio" value="radio4" id="radio4" name="radio"/><label for="radio4">RADIO 4</label>

<br/><br/>

<button onclick="selectRadio('radio1')">选中radio1</button>

<button onclick="selectRadio('radio2')">选中radio2</button>

<button onclick="selectRadio('radio3')">选中radio3</button>

<button onclick="selectRadio('radio4')">选中radio4</button>

<br/>

<br/>

</body>

<script type="text/javascript">

function selectRadio(radioId) {

var target = document.getElementById(radioId)

target.checked = true

}

</script>

</html>

单选这样写:<input ID="apple" name="fruit" type="radio" value ="Apple" /><Label for="apple">苹果</Label>

复选:

<input type="checkbox" name="fruit" value ="apple" ID="apple"><Label for="apple">苹果</Label>

如果多项的话,就直接for同样的ID,然后至少“苹果”变了文字而已,这个就是最好的方法了,没其他好的办法了

1、首先打开编辑器,然后新建一个html文件,编写入基本的框架。

2、然后用form,input和label创建一个单项选择题。

3、创建一个新的css文件,并且用link标签关联HTML文件。

4、然后撤销一下原来按钮的样式。

nput[type="radio"] {

  display: none

}

5、nput[type='radio'] + label:before{

  content: ""

  display: inline-block

  width: 20px

  height: 20px

  border: 2px solid gold

}

首先设置未点击的单选框样式,用border来设置颜色。

6、nput[type='radio']:checked + label:before{

  background-color: red

}

接着设置点击后的背景颜色,这里用background-color。

7、最后运行一下,完成效果图。


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

原文地址: http://www.outofmemory.cn/zaji/6118792.html

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

发表评论

登录后才能评论

评论列表(0条)

保存