我有两个单选按钮,其中一个输入文本,当我插入的值超过 12 时,它会自动检查 RadioBtn2
,否则它将检查 RadioBtn1
它工作正常,但是当我返回文本框并再次更改值时,它在刷新页面之前不起作用
$(function() {
$('#field222').change(function() {
var text_value = $("#field222").val();
if (text_value >= '12') {
$('input:radio[id="RadioBtn2"]').attr('checked', 'checked');
} else {
$('input:radio[id="RadioBtn1"]').attr('checked', 'checked');
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' class='input-lg' id='field222'>
<input type='radio' name='Radios' id='RadioBtn1' value='option1' checked>First
<input type='radio' name='Radios' id='RadioBtn2' value='option1' >Secend
最佳答案
那是因为 if 语句中的条件不正确。在进行大于检查之前,您需要将值解析为整数。
您还需要将change事件更改为keyup并将属性checked设置为true:
var text_value = parseInt($("#field222").val());
if (text_value >= 12) {
$('input:radio[id="RadioBtn1"]').prop("checked", true);
} else {
$('input:radio[id="RadioBtn2"]').prop("checked", true);
}
$(function() {
$('#field222').keyup(function() {
var text_value = parseInt($("#field222").val());
debugger;
if (text_value >= 12) {
$('input:radio[id="RadioBtn1"]').prop("checked", true);
} else {
$('input:radio[id="RadioBtn2"]').prop("checked", true);
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' class='input-lg' id='field222'>
<input type='radio' name='Radios' id='RadioBtn1' value='option1' checked>First
<input type='radio' name='Radios' id='RadioBtn2' value='option1' checked>Secend
关于javascript - 使用 JQuery 更改单选按钮检查状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52200968/