9-4這一節(jié)任務(wù)三求助輸入框按回車實(shí)現(xiàn)單選
<!DOCTYPE HTML>
<html> ?
<head> ?
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> ?
<title>9章-4練習(xí)</title> ?
</head> ?
?<body onload="clearall()">
? ? ? ? <form>
? ? ? ? ? 請(qǐng)選擇你愛好:<br>
? ? ? ? ? <input type="checkbox" name="hobby" id="hobby1"> ?音樂(lè)
? ? ? ? ? <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>
? ? ? ? ? <input type="button" value = "全選" onclick = "checkall();">
? ? ? ? ? <input type="button" value = "全不選" onclick = "clearall();">
? ? ? ? ? <p>請(qǐng)輸入您要選擇愛好的序號(hào),序號(hào)為1-6:</p>
? ? ? ? ? <input id="wb" name="wb" type="number" ?onKeyPress="if (event.keyCode == 13) checkone()">
<!--建議:把<input id = "wb" name = "wb" type = "text">中,type修改為 type="number"-->
<!--這樣只要用戶輸入了非數(shù)字,也能走代碼中1-6以外的輸入判定條件。-->
? ? ? ? ? <input name="ok" type="button" value="確定" onclick = "checkone();">
? ? ? ? </form>
? ? ? ? <script type="text/javascript">
? ? ? ? function checkall(){
? ? ? ? ?var hobby = document.getElementsByName("hobby");
for(var i=0;i<hobby.length;i++)
{
hobby[i].checked=true;
}
document.getElementById("wb").value="";
? ? ? ? }
? ? ? ? function clearall(){
?var hobby = document.getElementsByName("hobby");
for(var i=0;i<hobby.length;i++)
{
hobby[i].checked=false;
}
document.getElementById("wb").value="";
? ? ? ? }
? ? ? ? function checkone(){
var hobby = document.getElementsByName("hobby");
var j=document.getElementById("wb").value;
for(var i=0;i<hobby.length;i++)
{
hobby[i].checked=false;
}
? ? ? ? ? ??
if(j%1!=0){
? ? ? ? alert("你的輸入有誤\n正確的范圍在1~6的整數(shù)\n請(qǐng)重新輸入");//\n代表回車換行顯示文alert提示文字。
document.getElementById("wb").value="";//輸入有誤,清除輸入框
}
else if(j<1||j>6)
{
alert("你的輸入有誤\n正確的范圍在1~6的整數(shù)\n請(qǐng)重新輸入");
document.getElementById("wb").value="";//輸入有誤,清除輸入框
}
else?
{
hobby[j-1].checked=true
}
? ? ? ? ?// 任務(wù)3
? ? ? ? }
? ? ? ? window.onload=function()
{
clearall();
document.getElementById("wb").value="";
}
? ? ? ? </script>
? ? </body>
</html>
前兩個(gè)任務(wù),我用的document.getElementsByName("hobby")?
第三個(gè)任務(wù),我想添加一個(gè)輸入框輸入完數(shù)字以后,若按下回車鍵,就執(zhí)行后面"確定"按鈕所執(zhí)行的函數(shù),也就是函數(shù)checkone()。
我在代碼中加粗的那一行input里添加?onKeyPress="if (event.keyCode == 13) checkone()"? ?這一句代碼,用火狐瀏覽器調(diào)試的時(shí)候發(fā)現(xiàn),輸入框里輸入1-6的整數(shù)以后,回車,先是勾選了對(duì)應(yīng)的選項(xiàng),然后又像F5刷新瀏覽器一樣立馬去掉了勾選,請(qǐng)幫忙看看代碼哪里出了問(wèn)題。
2016-06-15
有個(gè)很簡(jiǎn)單的實(shí)現(xiàn)辦法:
改成
2016-06-03
不會(huì)呀