簡體   English   中英

提交時的JavaScript單選按鈕

[英]JavaScript Radio Buttons on Submit

所以我是JavaScript新手。 我正在嘗試創建一個簡單的代碼,該代碼將允許用戶選擇binaryhexoct並將十進制數字轉換為所選的單選按鈕。 現在,我現在不擔心轉換,我只是想讓代碼在提交后運行一個函數。 例如,如果選擇了單選按鈕二進制,則在單擊提交按鈕后,在頁面上應顯示“已選擇二進制”。

我真的迷失了如何使它工作並不確定在哪里看。 我一直在更改我的代碼,當您選擇它生成“選定對象”的按鈕時,它就起作用了,但是我希望它僅在按下提交按鈕后才生成。 不確定是否必須對提交按鈕或表單標簽進行編碼。 我當前無法正常工作的代碼如下:

 <!DOCTYPE html> <html> <head> <script> function convertit() { var conversion = document.getElementsByName('convert'); if (conversion[0].checked == true) { document.getElementById('test').innerHTML = "Binary Checked"; } else if (conversion[1].checked == true) { document.getElementById('test').innerHTML = " Hex Checked"; } else if (conversion[2].checked == true) { document.getElementById('test').innerHTML = "Oct Checked"; } else { alert("Empty"); } return true; } </script> </head> <body> <p id="test"> </p> <form onsubmit="return convertit();"> <input type="radio" value="binary" name="convert" id="binarybut" > Binary </input> <input type="radio" value="binary" name="convert" id="hexbut" > Hex </input> <input type="radio" value="hex" name="convert" id="octbut"> Oct </input> <input type="submit" value="Convert Number" > </form> </body> </html> 

您的Javascript找不到輸出元素,因為尚未聲明。

如果將<腳本> ... </ script>放在正文的末尾,它應該可以正常工作。

例如:

...
< /script>
< /body>

這是一個工作的小提琴

 <!DOCTYPE html> <html> <head> <script> function convertit() { if (document.getElementById('binarybut').checked) { alert("Binary Checked"); } else if (document.getElementById('hexbut').checked) { alert("Hexadecimal Checked"); } else if (document.getElementById('octbut').checked) { alert("Octal Checked"); } else { alert("Empty"); } return true; } </script> </head> <body> <p id="test"> </p> <form> <input type="radio" value="binary" name="convert" id="binarybut" > Binary </input> <input type="radio" value="binary" name="convert" id="hexbut" > Hex </input> <input type="radio" value="hex" name="convert" id="octbut"> Oct </input> <button type="button" onclick="convertit()">Convert</button> </form> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM