I have multiple html forms similar to the one below
<div >
<div >
<div >
<h3 >Form Four</h3>
</div>
<div >
<div >
<!-- Error messages can go here -->
</div>
<form novalidate>
<div>
<label for="password">Password : </label>
<input type="text" name="password" id="password" />
</div>
<div>
<label for="requiredPassword">Required and Password : </label>
<input type="text" name="requiredPassword" id="requiredPassword" />
</div>
<div>
<input type="submit" name="submitBtn" value="Validate" />
</div>
</form>
</div>
</div>
</div>
I am not allowed to change them. The issue I am having is that I can't get my event listeners to work. I am trying to have the button clicked for the specific form only validate that form and not the others.
This is what I have been trying to possibly work with based on other projects I have done with multiple buttons
document.querySelectorAll("input[name=submitBtn]").forEach(item => {
item.addEventListener('click', isAllValid)
//isAllValid is a function to check the inputs in the form
});
This isn't working, and I really need help trying to find out how to make this work. Thank you!
CodePudding user response:
To find the form that belongs to the button, inside isAllValid
, you can do this:
function isAllValid(event) {
const btn = event.target;
const form = btn.closest('form');
// ...
}
CodePudding user response:
One of the attributes of form elements is form
which returns a reference to the form to which each of these elements belongs.
See the following example with multiple forms.
var buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", (event) => {
event.preventDefault();
var msg = event.currentTarget.textContent;
var form = event.currentTarget.form;
console.log("'" msg "' clicked (" form.id ")");
return false;
});
});
button {
margin: 0.5rem;
}
<section>
<form id="firstForm" name="firstForm">
<button id="firstFormButton1">Button 1 (Form 1)</button>
<button id="firstFormButton2">Button 2 (Form 1)</button>
<button id="firstFormButton3">Button 3 (Form 1)</button>
</form>
</section>
<section>
<form id="secondForm" name="secondForm">
<button id="secondFormButton1">Button 1 (Form 2)</button>
<button id="secondFormButton2">Button 2 (Form 2)</button>
<button id="secondFormButton3">Button 2 (Form 2)</button>
</form>
</section>
<section>
<form id="thirdForm" name="thirdForm">
<button id="thirdFormButton1">Button 1 (Form 3)</button>
<button id="thirdFormButton2">Button 2 (Form 3)</button>
<button id="thirdFormButton3">Button 3 (Form 3)</button>
</form>
</section>