在Javascript中选择单选按钮时清除文本框字段 [英] Clearing a textbox field when a radio button is selected in Javascript
问题描述
我有一个Web表单,该表单允许用户使用预定义的单选按钮来捐款,并为其分配一个值(所有数字均不同).我也有一个自己选择的金额文本字段,他们可以用自己希望捐赠的自定义金额编写.如果用户选择了预定义的选项,我想清除自定义文本字段.
I have a web form which allows users to donate money using the predefined radio buttons with a value assigned to them (all different numbers). I also have a choose your own amount textfield which they can write in a custom amount they wish to donate. I want to clear the custom textfield if a user selects a predefined choice.
到目前为止,我已经创建了这个:
So far I have created this:
HTML:
<input type="radio" name="am_payment" value="3" checked="checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11" checked="checked"> <strong>100</strong>
<input type="radio" name="am_payment" value="32" checked="checked"> <strong>250</strong>
<input type="radio" value="" name="am_payment"><label>Other</label>
<input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/>
JAVASCRIPT:
$('input[name="am_payment"]').on('click', function() {
if ($(this).val() === '') {
$('#theamount').removeProp("disabled");
}
else {
$('#theamount').prop("disabled", "disabled");
$('input[name="CP_otheramount"]').val("");
}
});
但是基于value=""
的value === true
似乎并不正确.
But basing it on a value === true
for value=""
just doesn't seem right.
有没有办法改善这一点?
Is there a way to improve this?
谢谢
推荐答案
要禁用/启用元素,您需要将Disabled属性的值设置为true/false,因此删除该属性不起作用,因此您需要
To disable/enable an element you need to set the value of the disabled property to true/false, removing the property doesn't work so you need
>
$('input[name="am_payment"]').on('click', function() {
if ($(this).val() === '') {
$('#theamount').prop('disabled', false);
} else {
$('#theamount').prop("disabled", true).val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="am_payment" value="3" checked="checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11" checked="checked"> <strong>100</strong>
<input type="radio" name="am_payment" value="32" checked="checked"> <strong>250</strong>
<input type="radio" value="" name="am_payment">
<label>Other</label>
<input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled" />
这篇关于在Javascript中选择单选按钮时清除文本框字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!