HTML5必需属性是两个字段之一

编程入门 行业动态 更新时间:2024-10-26 22:28:50
本文介绍了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="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必需属性是两个字段之一

本文发布于:2023-11-07 04:19:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565558.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   属性   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!