我有一个包含两个必填输入字段的表单:
I have a form with two required input fields:
<form> <input type="tel" name="telephone" required> <input type="tel" name="mobile" required> <input type="submit" value="Submit"> </form>是否可以让浏览器验证,因此只需要其中一个?即如果电话被填满,不要抛出关于手机空的错误,反之亦然
Is it possible to get browsers to validate so only one of them is required? i.e if telephone is filled, don't throw an error about mobile being empty and vice versa
推荐答案我玩了一些想法现在有一个使用jQuery解决这个问题的工作方案:
I played around with some ideas and now have a working solution for this problem using jQuery:
jQuery(function ($) { var $inputs = $('input[name=telephone],input[name=mobile]'); $inputs.on('input', function () { // Set the required property of the other input to false if this input is not empty. $inputs.not(this).prop('required', !$(this).val().length); }); });
<script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form method="post"> Telephone: <input type="tel" name="telephone" value="" required> <br>Mobile: <input type="tel" name="mobile" value="" required> <br> <input type="submit" value="Submit"> </form>
这在两个输入上使用输入事件,当一个非空时,它将另一个输入的必需属性设置为false。
This uses the input event on both inputs, and when one is not empty it sets the required property of the other input to false.
我写了一个 jQuery插件包装上面的JavaScript代码,以便它可以用于多组元素。
I've written a jQuery plugin wrapping the above JavaScript code so that it can be used on multiple groups of elements.
更多推荐
HTML5必需属性是两个字段之一
发布评论