2

Apologies if this is a straightforward question, as I am still very new to JavaScript. I have a script that validates user inputs by checking if the text-field is empty. If it is not empty, then a confirmation window prompts the user to make sure they want to continue before the form is submitted and the information uploaded.

I would like to know how I can use the code below or similar code to validate multiple forms on the same page, as currently I can only get it to work with one single form? I have tried various solutions, non of which have yet been successful. I have even tried copy/pasting the entire script and changing the relevant elements inside it.

I've stripped my alterations to the code back to where it actually works correctly. Like I said, once I try to re-use it to validate multiple forms, the code stops working correctly.

// Set up event handlers in JavaScript
document.querySelector('form').addEventListener('submit', validationCheck);
document.getElementById('updateEventTitle').addEventListener('keyup', validationCheck);
// Get your DOM references just once, not every time the function runs
let eventTitle = document.getElementById('updateEventTitle');
let btnUpdate = document.getElementById('updateBtn');
function validationCheck(event) {
  if (eventTitle.value === '') {
    btnUpdate.disabled = true;
  } else {
    btnUpdate.disabled = false;
    //Confirmation window
    if (event.type === 'submit') {
      //Confirmation window
      var r = confirm('Do you want to update this item?');
      if (r == true) {
        window.location.href = 'server.php';
      } else {
        event.preventDefault();
      }
    }
  }
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
  <input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
  <input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
  <input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
  <input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
  <input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
  <input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>

I would like a script that is able to validate any HTML form on the page, not just the first one.

Many thanks.

2
  • Why not having just one form for all 3, as the action is always the same? Commented Jan 14, 2020 at 10:20
  • The feature is for a page which allows users to update information regarding upcoming events. I wasn't sure if a single form for all updatable content was suitable as the user would commonly only be updating one thing at a time. It made sense for me to therefor to split the content into separate forms but perhaps this is the wrong/overly complex approach? Commented Jan 14, 2020 at 10:40

1 Answer 1

1

We simply can took all the forms, loop through, get inputs and buttons we need for every form and set up listeners for every form, for every element.

Below is a code snippet explaining how it can be done.

// getting all forms
const elForms = [...document.querySelectorAll('form')];

// looping an array
elForms.map(elForm => {
  // Get your DOM references just once, not every time the function runs
  const elInput  = elForm.querySelector(`input[type='text']`);
  const elButton = elForm.querySelector(`input[type='submit']`);

  // Set up event handlers in JavaScript
  elForm.addEventListener('submit', (event) => validationCheck(event, elInput, elButton)); // passing parameters
  elInput.addEventListener('keyup', (event) => validationCheck(event, elInput, elButton)); // passing parameters
});

function validationCheck(event, elInput, elButton) {
    if(elInput.value==='') { 
        elButton.disabled = true; 
    } else { 
        elButton.disabled = false;

        //Confirmation window
        if(event.type === 'submit'){
            //Confirmation window
            var r =confirm('Do you want to update this item?');
            if (r==true)    {
                window.location.href = 'server.php';
            } else {
                event.preventDefault();
            }
        }
    }
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
     <input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
     <input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled> 
</form>

<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
     <input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/> 
     <input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled> 
</form>

<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
     <input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/> 
     <input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled> 
</form>

After answer

There are duplicating id in your example

<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
  <input type='text' id='updateEventTitle'

This is not valid and can cause problems in future. id should be unique.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.