Ahmad Ahmad - 7 months ago 18
Javascript Question

How to get elements values by class name and store them in an array in jQuery?

I am trying to get values from text boxes that are out of a

<form>
tag.
The three text boxes have the same class name. I want to get their values and use them later.

I am getting error for the alert part in
jQuery
below.

HTML

<input type="text" class="className">
<input type="text" class="className">
<input type="text" class="className">


jQuery

var $j_object = $(".className");
$j_object.each( function(i){
alert($j_object[i].val())
});

Answer

Try to use .eq(index) at this context,

var $j_object = $(".className");
$j_object.each( function(i){
  alert($j_object.eq(i).val());                     
});

Or you can use the this value inside of .each() to simplify the task,

var $j_object = $(".className");
$j_object.each( function(){
  alert($(this).val());                     
});

If you use bracket notation to access the jquery element collection, then that will return plain javascript object. And that won't have jquery functions in its prototype.

Comments