输入序号选择,但是我想选一个,另一个就自动清除,只显示一个框被选,怎么实现。
function checkone(){
var j=document.getElementById("wb").value;
var hobby = document.getElementById("hobby"+j);
hobby.checked = true;
<form> 请选择你爱好:<br> <input type="checkbox" name="hobby" id="hobby1" onclick="danxuan(this.id)"> 音乐 <input type="checkbox" name="hobby" id="hobby2" onclick="danxuan(this.id)"> 登山 <input type="checkbox" name="hobby" id="hobby3" onclick="danxuan(this.id)"> 游泳 <input type="checkbox" name="hobby" id="hobby4" onclick="danxuan(this.id)"> 阅读 <input type="checkbox" name="hobby" id="hobby5" onclick="danxuan(this.id)"> 打球 <input type="checkbox" name="hobby" id="hobby6" onclick="danxuan(this.id)"> 跑步 <br> <input type="button" value = "全选" onclick = "checkall();"> <input type="button" value = "全不选" onclick = "clearall();"> <p>请输入您要选择爱好的序号,序号为1-6:</p> <input id="wb" name="wb" type="text" > <input name="ok" type="button" value="确定" onclick = "checkone();"> </form> <script type="text/javascript"> // 复选框checkbox用作为单选框 function danxuan(thisid){ var hobby = document.getElementsByName("hobby"); var index; for (var i=1;i<hobby.length + 1;i++) { document.getElementById("hobby" + i).checked = false; } document.getElementById(thisid).checked = true; } // 任务1 function checkall(){ var hobby = document.getElementsByTagName("input"); for (var i=0;i<hobby.length-1;i++) hobby[i].checked=true; } // 任务2 function clearall(){ var hobby = document.getElementsByName("hobby"); for (var i=0;i<hobby.length-1;i++) hobby[i].checked=false; } // 任务3 function checkone(){ var j=0; j=parseInt(document.getElementById("wb").value); var hobby = document.getElementsByName("hobby"); switch(j){ case 1: hobby[0].checked=true; break; case 2: hobby[1].checked=true; break; case 3: hobby[2].checked=true; break; case 4: hobby[3].checked=true; break; case 5: hobby[4].checked=true; break; case 6: hobby[5].checked=true; break; default: break; } } </script>
仅供参考
我知道,radio是单选,看来是checkbox的固定属性,不能单选?
请选择你爱好:<br>
<input type="checkbox" name="hobby" id="hobby1"> 音乐
<input type="checkbox" name="hobby" id="hobby2"> 登山
<input type="checkbox" name="hobby" id="hobby3"> 游泳
<input type="checkbox" name="hobby" id="hobby4"> 阅读
<input type="checkbox" name="hobby" id="hobby5"> 打球
<input type="checkbox" name="hobby" id="hobby6"> 跑步 <br>
改为
请选择你爱好:<br>
<input type="radio" name="hobby" id="hobby1"> 音乐
<input type="radio" name="hobby" id="hobby2"> 登山
<input type="radio" name="hobby" id="hobby3"> 游泳
<input type="radio" name="hobby" id="hobby4"> 阅读
<input type="radio" name="hobby" id="hobby5"> 打球
<input type="radio" name="hobby" id="hobby6"> 跑步 <br>
把checkbox改为radio就可以了,checkbox是多选,radio是单选。(我个人建议是是学完HTML+CSS基础课程再来学这门课程会轻松许多)