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())
});
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())
});
Share
Improve this question
edited Apr 18, 2016 at 17:30
Rino Raj
6,2642 gold badges28 silver badges44 bronze badges
asked Apr 18, 2016 at 17:15
AhmadAhmad
331 silver badge5 bronze badges
1
-
1
replace the alert line with
alert($(this).val());
– Mohit Bhardwaj Commented Apr 18, 2016 at 17:23
2 Answers
Reset to default 4Try 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.
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./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">