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.
actionis always the same?