0

I have a foreach php like this:

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

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 
2
  • Maybe because your spelling of inputArray is inconsistent? Commented Oct 18, 2016 at 20:22
  • also, try just console.log(inputArray) Commented Oct 18, 2016 at 20:22

1 Answer 1

2

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) {
    console.log(input.value);
});
Sign up to request clarification or add additional context in comments.

5 Comments

I have just come to the awareness of the fact that Array.from(arrayLikeThingy) is much slower than [...arrayLikeThingy]
why slower? @Redu
This will depend on the JavaScript engine. Anyway, there is no practical difference in this situation at hand. You 'd need to have a node list with tens of thousands of elements before you could start noticing a difference.
@Diego Cespedes To be honest I can not tell exactly why but this morning i was trying some bench-marking and when i converted the [...x] into Array.from(x) on a code which was doing tons of it repeatedly, the resolution of the code prolonged more than double.
@trincot Agreed.. It was just my five cents for future reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.