根据复选框显示文本框

Show textbox based on the checkbox

本文关键字:文本 显示 复选框      更新时间:2023-09-26

我有一个问题,我有2个复选框,如果复选框的值为Y,我想显示一个文本框,我的代码:

<label>Admin:</label>
                <div class="onoffswitch">
                    <input type="checkbox" name="is_admin" class="onoffswitch-checkbox" value="Y" id="is_admin">
                    <label class="onoffswitch-label" for="is_admin">
                        <span class="onoffswitch-inner"></span>
                        <span class="onoffswitch-switch"></span>
                    </label>
                </div>
                <label>Verificator:</label>
                <div class="onoffswitch">
                    <input type="checkbox" name="is_verificator" class="onoffswitch-checkbox" value="Y" id="is_verificator">
                    <label class="onoffswitch-label" for="is_verificator">
                        <span class="onoffswitch-inner"></span>
                        <span class="onoffswitch-switch"></span>
                    </label>
                </div>
                <input type="text" style="display:none;" placeholder="" id="if_checked"/><br/>

我的jquery:

<script>
$("input[name=is_verificator]").change(function(){
    if($(this).val() == "Y")
    {
        $("#if_checked").show();
    }else{
        $("#if_checked").hide();
    }
});

只需将jquery代码封装在$(document).ready(function(){})中,如图所示:

<script>
$(document).ready(function(){
   $("input[name=is_verificator]").change(function(){
     if($(this).val() == "Y" && $(this).is(":checked"))  //changed this condition as per OP comment
     {
       $("#if_checked").show();
     }else{
       $("#if_checked").hide();
     }
  });
});
</script>

您正在查找.is(":checked")函数。

$(':checkbox[name="is_verificator"]').change(function(){
    if($(this).is(":checked"))
    {
        $("#if_checked").show();
    }else{
        $("#if_checked").hide();
    }
});