最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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">

发布评论

评论列表(0)

  1. 暂无评论