Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 required attribute one of two fields

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

like image 875
Andy Avatar asked Jun 25 '14 08:06

Andy


People also ask

When one field is filled other fields must be required?

if one field in the form is filled,all other fields must be filled or if none of the fields are filled then no need of checking validations. Iam using a method focus to add validations. once selecting a field,all fields are required validation executing.

What is the use of required attribute in html5?

The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

How do you make a button mandatory?

Select the field and click the Properties button (Gear Icon). 3. In the General tab, turn "ON" the Required feature.


1 Answers

Update 2020-06-21 (ES6):

Given that jQuery has become somewhat unfashionable in the JavaScript world and that ES6 provides some nice syntactic sugar, I have written a pure JS equivalent to the original answer:

document.addEventListener('DOMContentLoaded', function() {   const inputs = Array.from(     document.querySelectorAll('input[name=telephone], input[name=mobile]')   );    const inputListener = e => {     inputs       .filter(i => i !== e.target)       .forEach(i => (i.required = !e.target.value.length));   };    inputs.forEach(i => i.addEventListener('input', inputListener)); });
<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>

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.

Original Answer (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);     }); }); 

I've written a jQuery plugin wrapping the above JavaScript code so that it can be used on multiple groups of elements.

like image 102
Andy Avatar answered Sep 17 '22 15:09

Andy