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