I Have an html page and function is JS
I noticed that myForms is a NodeList with two elements, form is 0 or 1, How do I retrieve the input values for each form?
I also tried with
var query = '' + myForms[form].id + ' :input');
var $inputs = $(query);
But at the console level I have an error -> Uncaught TypeError: $inputs[0].val is not a function
function next() {
var arrayOutput = new Array();
var myForms = document.querySelectorAll('[id^="form-"]');
myForms.forEach(form=>{
var query = '#' + form.id + ' :input';
var $inputs = $(query);
var single = {};
single.name = $inputs[0].val();
single.yes = $inputs[1].val();
single.no = $inputs[2].val();
arrayOutput.push(single);
});
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<div class="container">
<div id="34">
<form id="form-34" method="post">
<div class="col-xs-3">
<div class="container">
<label> Model
<span>
<input type="text", id="name" name="name"/>
</span>
</label>
</div>
<input type="checkbox", id="yes" name="yes"/>
<input type="checkbox", id="no" name="no"/>
</div>
</form>
</div>
<div id="35">
<form id="form-35" method="post">
<div class="col-xs-3">
<div class="container">
<label> Model
<span>
<input type="text", id="name" name="name"/>
</span>
</label>
</div>
<input type="checkbox", id="yes" name="yes"/>
<input type="checkbox", id="no" name="no"/>
</div>
</form>
</div>
<button class="icon" onclick=next()>Next</button>
</div>
2
Answers
The error you’re getting:
Is because this returns a plain DOM element, not a jQuery object:
Though you can create a jQuery object from it:
Or, alternatively, don’t use jQuery’s
.val()
and just get the.value
from the DOM element.For example:
You can get all the forms on the page using
document.forms
. This returns a HTMLCollection that can be turned into an array using the Spread syntax (…).And then you can use the FormData constructor to get all the data in the form.