YSuraj
YSuraj

Reputation: 417

Textbox values as an array in jQuery?

Trying to store textbox values into different arrays. In my jQuery code array textA stores the textbox values of 'textA' and array textB must store the values of 'textB'. In the result, textB is containing the values of textbox 'textA' as well. As a result, I want only the values of textbox 'textB' in the array textB.

$(document).ready(function(){ 

  textA = textB = [];
 
  $('button').click(function(){
   $('input[name^=textA]').each(function(){
    textA.push($(this).val()); 
    $('span#textA').text(textA);
   });
 
   $('input[name^=textB]').each(function(){
    textB.push($(this).val());
    $('span#textB').text(textB);
   });
 textA = textB = [];
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textA" placeholder="Enter text A">
<input type="text" name="textA" placeholder="Enter text A"></br>
<input type="text" name="textB" placeholder="Enter text B">
<input type="text" name="textB" placeholder="Enter text B"></br>
<button>
Click
</button></br>
<span id="textA"></span></br>
<span id="textB"></span>

Upvotes: 0

Views: 1834

Answers (1)

Sudharsan S
Sudharsan S

Reputation: 15393

Assign as seperately textA = []; textB = [];

$(document).ready(function(){ 

  textA = [];
  textB = [];
 
  $('button').click(function(){
   $('input[name^=textA]').each(function(){
    textA.push($(this).val()); 
    $('span#textA').text(textA);
   });
 
   $('input[name^=textB]').each(function(){
    textB.push($(this).val());
    $('span#textB').text(textB);
   });
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textA" placeholder="Enter text A">
<input type="text" name="textA" placeholder="Enter text A"></br>
<input type="text" name="textB" placeholder="Enter text B">
<input type="text" name="textB" placeholder="Enter text B"></br>
<button>
Click
</button></br>
<span id="textA"></span></br>
<span id="textB"></span>

Upvotes: 5

Related Questions