jQuery 聚焦文本字段检查单选按钮
jQuery focus textfield check radio button
我正忙着做一个小表格,但我现在卡住了。
我有这个小代码:
jQuery('#textinput input').click(function() {
if (jQuery(this).is(':focus')) {
jQuery('input:radio[name=open_amount]').attr('checked',true);
} else {
jQuery('input:radio[name=open_amount]').attr('checked',false);
}
});
这是工作的一半。当我在输入文本中输入内容时,单选按钮将被检查,但如果我改变主意并检查其他一些单选按钮,则 HTML 代码中的检查不会被删除。
当我输入一个值时,改变主意并选中另一个单选按钮并返回到输入文本,单选按钮将不会自动更改。
所以我错了什么?
您必须使用 .focus
和 .blur
而不是 .click
您还必须使用 .prop
设置收音机 btn
jQuery(function() {
jQuery('#textinput input').focus(function() {
jQuery('input:radio[name=open_amount]').prop('checked', true);
});
jQuery('#textinput input').blur(function() {
jQuery('input:radio[name=open_amount]').prop('checked', false);
});
//Suggestion: You can add this so that when user clicks on the radio btn, it will fucos on the textbox
jQuery('input:radio[name=open_amount]').click(function(){
jQuery('#textinput input').focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="textinput">
<input type="text">
</div>
<input type="radio" name="open_amount" />
我正忙着做一个小表格,但我现在卡住了。
我有这个小代码:
jQuery('#textinput input').click(function() {
if (jQuery(this).is(':focus')) {
jQuery('input:radio[name=open_amount]').attr('checked',true);
} else {
jQuery('input:radio[name=open_amount]').attr('checked',false);
}
});
这是工作的一半。当我在输入文本中输入内容时,单选按钮将被检查,但如果我改变主意并检查其他一些单选按钮,则 HTML 代码中的检查不会被删除。
当我输入一个值时,改变主意并选中另一个单选按钮并返回到输入文本,单选按钮将不会自动更改。
所以我错了什么?
您必须使用 .focus
和 .blur
而不是 .click
您还必须使用 .prop
设置收音机 btn
jQuery(function() {
jQuery('#textinput input').focus(function() {
jQuery('input:radio[name=open_amount]').prop('checked', true);
});
jQuery('#textinput input').blur(function() {
jQuery('input:radio[name=open_amount]').prop('checked', false);
});
//Suggestion: You can add this so that when user clicks on the radio btn, it will fucos on the textbox
jQuery('input:radio[name=open_amount]').click(function(){
jQuery('#textinput input').focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="textinput">
<input type="text">
</div>
<input type="radio" name="open_amount" />