当复选框被选中时,如何禁用html所需的验证

How to disable html required validation when checkbox is checked?

本文关键字:html 何禁用 验证 复选框      更新时间:2023-09-26

我有这个现有的功能:当复选框未选中时,它将显示ul部分

  <input type="checkbox" id="cb_ship" onclick="toggle('.ship', this)" checked="checked">
  <label for="cb_ship" >Same as account name</label>

 <form method="post">  
      <ul class="ship" style="display:none;">
       <li> fname <input type="text" name="fname" required></li>
       <li> lname <input type="text" name="lname" required></li>
       <li> age <input type="text" name="age" required></li>
       <li> address <input type="text" name="address" required></li>
       <li> city <input type="text" name="city" required></li>
       <li> <input type="submit" value="send"></li>
      </ul>
  </form>

JS:

function toggle(className, obj) {
        var $input = $(obj);
        if ($input.prop('checked'))
            $(className).hide();
        else $(className).show();
    }

我想做的:如果复选框被选中,所有必需的属性应该被禁用而不单击复选框。这样我就可以提交表格了。

你的函数将是这样的

  function toggle(className, obj) {
  var attr = false;
    if  (obj.is(':checked')){
        attr = true;
    }
    $("."+className+" li input").each(function(){
        $(this).prop('disabled', attr);
    });
}

但是在复选框中你必须删除点(.ship)因为它会产生错误并为对象添加$ onclick="toggle('ship', $(this))

删除属性?

$('.ship').find('input').removeAttr( "required");

或禁用输入?

$('.ship').find('input').prop('disabled', true);

$('.ship').find('input').removeAttr( "required").prop('disabled', true);

像这样使用它们:

function toggle(className, obj) {
    var $input = $(obj);
    if ($input.prop('checked'))
        $(className).hide().find('input').removeAttr("required").prop('disabled', true);
    else $(className).show().find('input').attr( "required",true).prop('disabled', false);
}

要处理由于在该点设置了"required"而希望处理页面启动逻辑的情况,请从标记中删除处理程序,将其放入代码中,然后触发它:

<input type="checkbox" id="cb_ship" checked="checked">
<label for="cb_ship">Same as account name</label>
<form method="post">
  <ul class="ship" style="display:none;">
    <li> fname
      <input type="text" name="fname" required>
    </li>
    <li> lname
      <input type="text" name="lname" required>
    </li>
    <li> age
      <input type="text" name="age" required>
    </li>
    <li> address
      <input type="text" name="address" required>
    </li>
    <li> city
      <input type="text" name="city" required>
    </li>
    <li>
      <input type="submit" value="send">
    </li>
  </ul>
</form>

查看我触发处理程序的最后一部分:

function toggle(className, obj) {
  var $input = $(obj);
  if ($input.prop('checked')) {
    console.log("checked");
    $(className).hide().find('input').removeAttr("required").prop('disabled', true);
  } else $(className).show().find('input').attr("required", true).prop('disabled', false);
}
$('#cb_ship').on('click change', function() {
  toggle('.ship', this);
}).trigger('change');