【问题标题】:JavaScript Radio Buttons on Submit提交时的 JavaScript 单选按钮
【发布时间】:2017-04-28 01:17:08
【问题描述】:

所以我是 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>

【问题讨论】:

  • 您的代码没问题,只需从处理程序返回false,这样就可以防止默认表单提交。您的表单正在提交,导致页面刷新,因此它将进入默认状态
  • 非常感谢!很高兴这是一个简单的修复,我整天都在发疯试图让它工作。谢谢!!!成功了!

标签: javascript forms radio-button form-submit


【解决方案1】:

<!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>

【讨论】:

  • @ssheatler 回答你的问题,你可以运行代码并尝试 CSS 可以在完成功能后完成
  • 祝你好运,这就是你所需要的@ssheatler
【解决方案2】:

您的 Javascript 找不到您的输出元素,因为它尚未声明。

如果您将 ... 放在正文的末尾,它应该可以正常工作。

例如:

...
< /script>
< /body>

Here's a working fiddle

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 2021-06-09
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多