启用单选按钮在加载时勾选

Enable Radio Button Checked On Load

本文关键字:加载 单选按钮 启用      更新时间:2023-09-26

我想确保"Email"单选按钮在加载时被选中,而不是在手机上。

出于某种原因,"电话"单选按钮被选中,但两个输入都显示,我不太明白。

演示

这是我的jQuery

var ebuForm = {
        init : function() {
            ebuForm.showInput();
        },
        showInput : function(e) {
            var radioInput = $("input[type='radio']"),
                emailRadio = $("input[value='email']");
            radioInput.prop('checked', true);
            radioInput.change(function(){
                var emailInput = $('.email-input'),
                    phoneInput = $('.phone-input');
                if($(this).val()=="email") {
                    emailInput.show();
                    phoneInput.hide();
                    console.log('Email Enabled');
                } else {
                    emailInput.hide();
                    phoneInput.show();
                    console.log('Phone Enabled');
                }
            });
        }
};
$(function() {
    ebuForm.init();
});

工作演示 http://jsfiddle.net/2F88K/ http://jsfiddle.net/775X2/

  • 变更事件顺序
  • 触发change事件就可以了。

如果我可以建议:试着把你的更改事件放在外面。见radioInput.prop('checked', true).trigger("change");

radioInput.prop('checked', true)的使用是一种有趣的,我不鼓励。:)认为单选按钮是either / or,即两个中的一个将被选中。

希望休息适合你的需要。:)

var ebuForm = {
        init : function() {
            ebuForm.showInput();
        },
        showInput : function(e) {
            var radioInput = $("input[type='radio']"),
                emailRadio = $("input[value='email']");
            radioInput.change(function(){
                var emailInput = $('.email-input'),
                    phoneInput = $('.phone-input');
                if($(this).val() =="email") {
                    emailInput.show();
                    phoneInput.hide();
                    console.log('Email Enabled');
                } else {
                    emailInput.hide();
                    phoneInput.show();
                    console.log('Phone Enabled');
                }
            });
            radioInput.prop('checked', true).trigger("change");
        }
};
$(function() {
    ebuForm.init();
});

首先input[value='email']不是一个很好的选择器——使用#email代替。选中电话单选按钮的原因是因为您正在使用以下代码进行选中:

        radioInput.prop('checked', true);

你可能想写:

       emailRadio.prop('checked', true);

请记住,您不能同时检查phoneemail !它们都有相同的name

试试这个

JS小提琴

关键是$('#email').prop('checked', true).trigger('change');

有很多方法…

解决方案#1:(HTML)

你可以使用checked="checked"

<

JSFiddle演示/strong>

解决方案#2:(JQuery)

var email = $("#email");
email.prop('checked', true);

和隐藏手机输入页面加载,您可以trigger change事件:

email.prop('checked', true).trigger('change');
<

JSFiddle演示/strong>