Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all input fields inside div (without JS library)

What's the easiest way to get all input fields inside a div without using a javascript library like jQuery? Similar to this jQuery snippet:

var inputs = $('#mydiv :input');
like image 992
apparat Avatar asked Aug 27 '10 16:08

apparat


4 Answers

document.getElementById('mydiv').getElementsByTagName('input')
like image 58
Roy Sharon Avatar answered Mar 21 '23 03:03

Roy Sharon


querySelector and querySelectorAll will fetch the details of what you're expecting easily.

var divElem = document.getElementById("myDiv");
var inputElements = divElem.querySelectorAll("input, select, checkbox, textarea");

It will give all the input, select, textarea elements in array format.

like image 24
Vishnu Prasanth G Avatar answered Mar 21 '23 03:03

Vishnu Prasanth G


Try:

var inputs = document.getElementById('mydiv').getElementsByTagName('input');
like image 35
Andrei Serdeliuc ॐ Avatar answered Mar 21 '23 05:03

Andrei Serdeliuc ॐ


If you are on modern browsers (ie9+) you can take advantage of querySelectorAll‎.

var inputs = document.querySelectorAll‎('#myDiv input');

or if you already have the div, you can use it directly

var inputs = myDiv.querySelectorAll('input');
var inputs = myDiv.getElementByTagName('input');

either will work. To serialize you can do this once you have your inputs

var values = {}
for (const input of inputs){
   values[input.name] = input.value
}
like image 27
Fresheyeball Avatar answered Mar 21 '23 04:03

Fresheyeball