Diego Cespedes Diego Cespedes - 1 year ago 54
Javascript Question

Javascript - Create array with inputs values

I have a foreach php like this:

@foreach($posts as $post)
<img src="{{$post->image}}" width="150" height="150">
<input type="hidden" class="postId" value="{{$post->id}}" name="postId">
<p class="expiredate">{{$post->expire_date}}</p>
<p class="current">{{$current}}</p>

I would like do an array javascript with values of inputs hiddens, like this:

var inputsArray= [value first input, value second input, value....]

i'm tryng like this:

var d = document;
var inputsArray = d.querySelectorAll('.postId');

but it doen't work, my console give me:

console.log(inputArray.value) = undefined

Answer Source

You need to convert your variable to a true array, since querySelectorAll returns a node list, not an array. Then iterate over that array, as the array itself has no value property:

var d = document;    
var inputsArray = Array.from(d.querySelectorAll('.postId'));

inputsArray.forEach(function (input) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download