Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent form submission if only one out of two paired inputs is filled out

I have a pair of inputs. I have no problem with a user leaving the both of them blank. But what I need is a way to force the user to fill the second input field if he decides to fill the first input field and vice versa(or prevent form submission in the event of that).

Here are my input elements:

<input name="cas[]" id="ca">
<input name="exams[]" id="exam">

<button type="submit" id="submit">Submit</submit>

I would also appreciate if there is also an implementation for multiple input pairs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A simple script like this should do the trick:

var cas = document.getElementById("ca");
var exams = document.getElementById("exam");

cas.onkeyup = function() {nosubmit()}
exams.onkeyup = function() {nosubmit()}

function nosubmit() {
  if ((cas.value != "" && exams.value == "") || (cas.value == "" && exams.value != "")) {
    document.getElementById("submit").disabled = true;
  } else {
    document.getElementById("submit").disabled = false;
  }
}
<input name="cas[]" id="ca">
<input name="exams[]" id="exam">

<button type="submit" id="submit">Submit</submit>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading