【问题标题】:How to enable text field when clicked based on radio button如何在基于单选按钮单击时启用文本字段
【发布时间】:2017-03-14 15:59:41
【问题描述】:

我有一个文本字段和其他三个单选按钮。

无论是从文本框中填写的自定义金额还是通过单击具有固定值的单选按钮,我都必须添加捐款金额。

<input type="radio" name="type" value = '1'>$1<br>
<input type="radio" name="type" value = '5'>$5<br>
<input type="radio" name="type" value = '10'>$10<br>
<input type = "number" id ="custom_amount">

我想在单击任何单选按钮时禁用输入字段,当我单击文本字段时它会启用。

有可能做到吗?正如我尝试使用

<input type="radio" name="type" value = '1' id = 'id_1' onclick="document.getElementById('id_1').disabled = false; document.getElementById('custom_amount').disabled = true;">$1<br>
<input type="radio" name="type" value = '5' id = 'id_5' onclick="document.getElementById('id_5').disabled = false; document.getElementById('custom_amount').disabled = true;">$5<br>
<input type="radio" name="type" value = '10' id = 'id_10' onclick="document.getElementById('id_10').disabled = false; document.getElementById('custom_amount').disabled = true;">$10<br>
<input type = "number" id ="custom_amount">

【问题讨论】:

  • value = 1 先把它改成value="1"

标签: javascript php jquery html


【解决方案1】:

您尝试遵循的模式不是标准,因为它涉及从单选组中删除选择。虽然这是可能的,但这不是无线电组的预期用途,也不是很好的代码。

因此,通常的做法是包含一个额外的单选按钮,该按钮在选中时启用/禁用输入。像这样的:

$('.radio').change(function() {
  $('#custom_amount').prop('disabled', !$(this).is('.other'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="radio" name="type" class="radio" value="1">$1</label>
<label><input type="radio" name="type" class="radio" value="5">$5</label>
<label><input type="radio" name="type" class="radio" value="10">$10</label>
<label><input type="radio" name="type" class="radio other" value="">Other:</label>
<input type="number" id="custom_amount" disabled="true">

【讨论】:

  • 请详细说明“它不起作用”。控制台有错误吗?
  • 其实并没有报错,实际上并没有提醒什么
  • 加载资源失败:服务器响应状态为 500(服务不可用(带有消息))未捕获的 ReferenceError: $ is not defined at test.php:3
  • 500是与JS代码无关的服务器端错误。 $ 未定义意味着您没有在页面中正确包含 jQuery.js
【解决方案2】:

你可以像下面这样简单地做。默认情况下,输入元素是不被禁用的,当任何一个单选按钮被点击时,输入框将被禁用

<!DOCTYPE html>
<html>
<head>
    <title> Radio buttons input </title>
</head>
<body>
	<input type="radio" class="radio" name="type" value = 1>$1<br>
	<input type="radio" class="radio" name="type" value = 5>$5<br>
	<input type="radio" class="radio" name="type" value = 10>$10<br>
	<input type = "number" id ="custom_amount" >
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


    <script>
   $('.radio').on("click",function(){
   	   $('#custom_amount').val($(this).val());
        $('#custom_amount').attr("disabled","disabled");
        console.log($('#custom_amount').val());
   });
    </script>
</body>
</html>

【讨论】:

  • 感谢您的回答,但您提供的解决方案并不是我们真正想要执行的。
猜你喜欢
  • 2012-05-23
  • 2018-06-18
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 1970-01-01
相关资源
最近更新 更多