繁体   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