【问题标题】:Enable/Disable input by radio selection with jquery使用 jquery 通过单选启用/禁用输入
【发布时间】:2020-04-28 12:29:54
【问题描述】:

带有单选按钮的表单。如果选中“Existing”,将启用“existingnumber”输入。它在选择过程中工作正常,但在加载时不起作用。加载时,输入“existingnumber”保持禁用状态,即使它已“选中”。这在提交表单时会出现问题,并且错误验证失败。我已经尝试在最后附加 .change() ,并创建一个我在准备好的文档上调用的函数,但这没有用。我想我错过了一些东西。也许我需要先获得价值?我有点jquery noob。

<input type="radio" name="officephone" value="New" id="officephonenew" >
<label for="officephonenew">New</label><br>

<input type="radio" name="officephone" value="Existing" id="officephoneexisting" checked>
<label for="officephoneexisting">Existing</label><br>

<input type="text" name="existingnumber" placeholder="555-555-1234" /><br>

<input type="radio" name="officephone" value="No" id="officephoneno">
<label for="officephoneno">Not required</label>
$('input:radio[name="officephone"]').change(function(){
    $('input[name="existingnumber"]').prop("disabled",true);
    if($(this).attr('value') == 'Existing') {
        $('input[name="existingnumber"]').prop("disabled", false);
    }
});

https://jsfiddle.net/Cormang/sd8xaj9h/10/

【问题讨论】:

    标签: javascript html jquery forms


    【解决方案1】:

    要使这项工作在负载下工作,只需使用filter() 检索选中的单选按钮和trigger() 上的change 事件。

    还请注意,您可以通过将条件的布尔输出提供给disabled 属性并使用val() 来简化逻辑。

    $('input:radio[name="officephone"]').change(function() {
      $('input[name="existingnumber"]').prop("disabled", $(this).val() != 'Existing');
    }).filter(':checked').trigger('change');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="radio" name="officephone" value="New" id="officephonenew" />
    <label for="officephonenew">New</label><br />
    
    <input type="radio" name="officephone" value="Existing" id="officephoneexisting" checked />
    <label for="officephoneexisting">Existing</label><br />
    <input type="text" name="existingnumber" placeholder="555-555-1234" disabled /><br />
    
    <input type="radio" name="officephone" value="No" id="officephoneno" />
    <label for="officephoneno">Not required</label>

    【讨论】:

    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 2010-11-27
    • 2016-03-09
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多