Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Javascript - Create array with inputs values

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 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...