简体   繁体   English

HTML5必需的输入,删除和添加即时无效

[英]HTML5 Required input, removing and adding on the fly not working

I am trying to remove a required attribute from an input on the fly. 我试图从动态输入中删除所需的属性。 The general idea is I have a field that is set to required, this field has custom validation with the pattern attribute. 一般的想法是我有一个设置为必需的字段,该字段具有pattern属性的自定义验证。 When the user clicks a button I am attempting to remove the required field. 当用户单击按钮时,我试图删除所需的字段。

I have put together a fiddle here: https://jsfiddle.net/paulmatos/t1p1wub3/ 我在这里放了一个小提琴: https//jsfiddle.net/paulmatos/t1p1wub3/

HTML: HTML:

<form>

    <input type="text" oninvalid='this.setCustomValidity("Enter a number in the Specified Range");' oninput="try{setCustomValidity('')}catch(e){}" pattern="[0-9]" required="required" name="password" id="password" />

    <input type="text" required="required" name="temp" />

    <input type="submit" class="btn btn-primary form-control" value="Submit" />

    <div class="btn btn-default removeReq">Remove Required</div>

</form>

Jquery: jQuery的:

$('.removeReq').click(function() {
  $('#password').removeAttr('required');
});

The issue I am experiencing has to do with the order of submission. 我遇到的问题与提交顺序有关。

If you click remove required, and then submit the form you will see that it works as intended. 如果单击“删除必需”,然后提交表单,您将看到它按预期工作。 However, if you do those steps in reverse order, click submit first, then remove and try and submit again, you will notice I am still getting the validation error on the first input. 但是,如果您按相反的顺序执行这些步骤,请先单击“提交”,然后再次删除并尝试再次提交,您会注意到我仍然在第一次输入时收到验证错误。

Is there anyway to get around this with this intended functionality, I am trying to get this to work just with the html5 validation. 无论如何使用这个预期的功能来解决这个问题,我试图通过html5验证来实现这一点。

Think you are getting this due to the code in the oninvalid handler. 认为你是因为oninvalid处理程序中的代码而得到这个。 Try this. 尝试这个。

$('.removeReq').click(function() {
  $('#password').removeAttr('required oninvalid');
});

You can try this instead of removeAtt(): 你可以试试这个而不是removeAtt():

$('.removeReq').click(function() {
  $('#password').prop('required', false);
});

I did have a look at the fiddle and the only way I could get the behaviour you wanted was by literally detaching, cloning and reinserting the field. 我确实看过这个小提琴,唯一可以获得你想要的行为的方法是通过字面分离,克隆和重新插入这个领域。 Works tho. 工作。

$('.removeReq').click(function() {
  var password = $('#password').removeAttr('required oninvalid oninput pattern').detach().clone();
  $('form').prepend(password);
});

https://jsfiddle.net/t1p1wub3/2/ https://jsfiddle.net/t1p1wub3/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM