Bineesh
Bineesh

Reputation: 494

How to read dom element value by jquery

Im trying to read every element in the same name. I tried to iterate using each as under

var subarray=[];
$('.subjects').each(function() {
  subarray[counter] = $('.subjects').val();
  counter = counter + 1;                
});

But how can we refer or point to the value in the specific (one by one ) element in it. ? To clarify, there are 5 inputs having same name . And i want to read values of each of those elements.

Upvotes: 0

Views: 133

Answers (3)

Balvinder Singh
Balvinder Singh

Reputation: 320

Please use this one

var subarray= [];
$("input[name='subjects[]']").each(function() {
subarray.push($(this).val());
});

Upvotes: 1

PHELMS
PHELMS

Reputation: 155

$('.subjects').each(function(_element){
    subarray[counter]=$(this).val();
counter=counter+1;              
});

You would want to use either the $(this) handled that jQuery provides, or add a variable in the function as shown with the _elment variable.

Upvotes: 1

kind user
kind user

Reputation: 41893

Use this keyword to reference to the each element in the collection.

Or you can just use Array#push to store each element inside newly created arr.

var arr = [];
$('.subjects').each(function(){
  console.log($(this).val());      
  arr.push($(this).val());
});

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='subjects' type='text' value='1'>
<input class='subjects' type='text' value='2'>
<input class='subjects' type='text' value='3'>

Upvotes: 1

Related Questions