下面這段代碼,是之前咨詢過的一段。
作用是點擊checkbox選中/取消選中后,在input中顯示對應的選項。
能正常使用。
<!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>
<title>JS點擊checkbox傳值到input</title>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
<script type="text/javascript">
function checkedfun() {
var p = document.getElementById("jsrtxt");
var str = this.parentNode.innerText + ";";
if (this.checked) {
p.value += str;
} else {
p.value = p.value.replace(str,"");
}
}
window.onload = function () {
var arr = document.querySelectorAll("input[name=aaa]");
for (var i = 0; i < arr.length; i++) {
arr[i].onclick = checkedfun;
}
}
</script>
</head>
<body>
<input type="text" id="jsrtxt" class="tip" />
<label><input type="checkbox" name="aaa" value="https://bbs.csdn.net/topics/a1"/>復選1</label>
<label><input type="checkbox" name="aaa" value="https://bbs.csdn.net/topics/a2"/>復選2</label>
<label><input type="checkbox" name="aaa" value="https://bbs.csdn.net/topics/a3"/>復選3</label>
</body>
</html>
現在想請教的是:
1、代碼開頭添加<?php $moren="a2,a1,"; ?>
2、并且給對應的checkbox添加checked
——相當于默認選中a2和a1
如下
<?php $moren="a2,a1,"; ?>
<!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>
<title>JS點擊checkbox傳值到input</title>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
<script type="text/javascript">
function checkedfun() {
var p = document.getElementById("jsrtxt");
var str = this.parentNode.innerText + ";";
if (this.checked) {
p.value += str;
} else {
p.value = p.value.replace(str,"");
}
}
window.onload = function () {
var arr = document.querySelectorAll("input[name=aaa]");
for (var i = 0; i < arr.length; i++) {
arr[i].onclick = checkedfun;
}
}
</script>
</head>
<body>
<input type="text" id="jsrtxt" class="tip" />
<label><input type="checkbox" name="aaa" value="https://bbs.csdn.net/topics/a1"/ checked>復選1</label>
<label><input type="checkbox" name="aaa" value="https://bbs.csdn.net/topics/a2"/ checked>復選2</label>
<label><input type="checkbox" name="aaa" value="https://bbs.csdn.net/topics/a3"/>復選3</label>
</body>
</html>
勞煩幫敲一下代碼,抱拳感謝~
uj5u.com熱心網友回復:
<?php $moren="a2,a1,"; ?>
...
window.onload = function () {
var arr = document.querySelectorAll("input[name=aaa]");
var v = ",<?php echo $moren?>,";
for (var i = 0; i < arr.length; i++) {
arr[i].onclick = checkedfun;
var item = "," + arr[i].value + ",";
if (v.indexOf(item) != -1) arr[i].checked = true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/195686.html
標籤:JavaScript
