HTML5必需属性是两个字段之一 [英] HTML5 required attribute one of two fields

查看:223
本文介绍了HTML5必需属性是两个字段之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个必填输入字段的表单:

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="https://ajax.googleapis.com/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必需属性是两个字段之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆