I saw a similar post here, however I want to do something similar using javascript. Basically there a method to grab all user input in some container such as a div or form
<form>
<div>
<text>
</div>
<div>
<textarea>
</div>
<div>
<select>
</div>
</form>
An example would be to grab text, textarea, select, and other forms of user input. I saw something like
var elements = document.myform.getElementsByTagName("input")
But it wouldn't work for selects. I know I could possibly just have a duplicate method which attempts to find ("select") but what if the form must keep the order in which user put in information.
EDIT: Thank you for all the responses. Does all the methods mentioned so far only work if the inputs are direct descendants or is there some other method?
You can use a query selector.
document.querySelectorAll('#divID input, #divID select, #divID textarea');
//selects all elements contained by #divId that are input, textarea, or select elements
<div id="myDiv">
<form>
<input type="text">
<select>
<option>1</option>
</select>
<textarea>Text...</textarea>
<div>
<span>
<select id="nestedSelect"></select>
</span>
</div>
</form>
</div>
<script>
var inputs = document.querySelectorAll('#myDiv input, #myDiv select, #myDiv textarea');
for(let i = 0; i < inputs.length; i++){
console.log(inputs[i]);
}
</script>
You can also get the div
or form
first and then use querySelectorAll
on it to get all the input
s, select
s and textarea
s contained by it (not just direct children).
<div id="myDiv">
<form>
<input type="text">
<select>
<option>1</option>
</select>
<textarea>Text...</textarea>
<div>
<input type="text"/>
</div>
<div>
<span>
<select id="nestedSelect">
<option value="2">2</option>
</select>
</span>
</div>
</form>
</div>
<script>
var divElem = document.getElementById("myDiv");
var inputElements = divElem.querySelectorAll("input, select, textarea");
for(let i = 0; i < inputElements.length; i++){
console.log(inputElements[i]);
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With