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

JavaScript010

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>

这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />

<title>JQuery radio</title>

<script type="text/javascript" language="javascript" src="JavaScript/jquery-1.6.1.min.js" ></script>

<script type="text/javascript">

$(function () {

$("input").click(function () {

if ($(this).attr("checked")) {

alert("选中了")

}

})

})

</script>

</head>

<body>

<input type="radio"/>

</body>

</html>

扩展资料:

注意事项

<form>

<input type="radio" id="radio1" />

<input type="button" οnclick="check()" value="选中" />

<input type="button" οnclick="uncheck()" value="取消" />

</form>

function check() {

//被选中

document.getElementById("radio1").checked = true

//被选中时,可以执行的方法

if(document.getElementById("radio1").checked == true){

  console.log('==')

}

}

function uncheck() {

//不选中

document.getElementById("radio1").checked = false

//不被选中时,可以执行的方法

if(document.getElementById("radio1").checked == false){

  console.log('++')

}

}