【发布时间】:2017-04-28 01:17:08
【问题描述】:
所以我是 JavaScript 新手。我正在尝试创建一个简单的代码,允许人们选择binary、hex 或oct,并将十进制数字转换为所选单选按钮。现在我不担心此时的转换,我只是想让代码在我点击提交后运行一个函数。例如,如果选择了二进制单选按钮,则单击提交按钮后,页面上应显示“已选择二进制”。
我真的不知道如何让它工作,不知道在哪里看。我不断更改我的代码,当您选择它生成“对象选定”的按钮时,我让它工作,但我希望它仅在按下提交按钮后生成。不确定我是否必须对提交按钮或表单标签进行编码。我当前的非工作代码如下:
<!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>
【问题讨论】:
-
您的代码没问题,只需从处理程序返回
false,这样就可以防止默认表单提交。您的表单正在提交,导致页面刷新,因此它将进入默认状态 -
非常感谢!很高兴这是一个简单的修复,我整天都在发疯试图让它工作。谢谢!!!成功了!
标签: javascript forms radio-button form-submit