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
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.
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.
Select the field and click the Properties button (Gear Icon). 3. In the General tab, turn "ON" the Required feature.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With