PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 30, 2022

[FIXED] How can I have a XNOR-like behaviour on required input?

 September 30, 2022     bootstrap-5, forms, html, javascript     No comments   

Issue

I have the following form:

<form>
        <input type="text" name="input1">
        <input type="text" name="input2">
        <button type="submit">submit</button>
    </form>

Using Bootstrap, I am trying to prevent the user from inputting only 1 field ; i.e. Not inputting anything is fine, inputting both fields is fine, inputting one field but not the other is not fine.
I read Validation but could not find a solution to my problem.
What is the best way to solve this issue ?


Solution

You can compare the comparisons with an empty string to tell if they're both empty or both non-empty.

document.querySelector("form").addEventListener("submit", e => {
  let value1 = document.querySelector('[name=input1]').value;
  let value2 = document.querySelector('[name=input2]').value;
  if ((value1 == '') != (value2 == '')) {
    e.preventDefault();
    console.log('Fill in both inputs or neither');
  } else {
    e.preventDefault(); // just for snippet here
    console.log('Form was submitted');
  }
});
<form>
  <input type="text" name="input1">
  <input type="text" name="input2">
  <button type="submit">submit</button>
</form>



Answered By - Barmar
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing