Reputation: 33
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())
});
Upvotes: 3
Views: 8775
Reputation: 6264
You can save the textbox values to array using .map()
function in jQuery.
Working Example
var array = $('.className').map(function(){
return $(this).val()
}).get();
alert(array)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="className" value="1">
<input type="text" class="className" value="2">
<input type="text" class="className" value="3">
Upvotes: 3
Reputation: 67207
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.
Upvotes: 4