nasty
nasty

Reputation: 7077

Use array data in each loop jQuery

This is my array and each loop. I want to look for each input field with a specific class and set its value. Can you guys see why this isnt working?

var inputTextIDs = [
  [".hotelLocaiton", "Location"],
  ["#agentTransfersSearchForm_filter_transfersName", "Location"]

 ];

$.each(inputTextIDs,function(i,v){
     $('input'+inputTextIDs[i]).val(inputTextIDs[v]);
}); 

Upvotes: 0

Views: 43

Answers (2)

Muhammad Inaam Munir
Muhammad Inaam Munir

Reputation: 1260

In $.each(inputTextIDs,function(i,v){, 'i' is index and 'v' is value. So, i will be 0,1,2 and v will be equal to values in the array. Here in your case you have arrays in a big array. So, inputTextIDs[0] will get the first array in big array i.e. [".hotelLocaiton", "Location"], then inputTextIDs[0][0] will get first value in this array i.e. '.hotelLocation' and inputTextIDs[0][1] will get 'Location'.

So, following code will work:

var inputTextIDs = [
  [".hotelLocaiton", "Location"],
  ["#agentTransfersSearchForm_filter_transfersName", "Location"]

 ];

$.each(inputTextIDs,function(i,v){
     $('input'+inputTextIDs[i][0]).val(inputTextIDs[i][1]);
});

Upvotes: 0

Shiladitya
Shiladitya

Reputation: 12181

Here you go with the solution https://jsfiddle.net/sae7mv3e/

var inputTextIDs = [
  [".hotelLocaiton", "Location"],
  ["#agentTransfersSearchForm_filter_transfersName", "Location"]

 ];
 


$.each(inputTextIDs,function(i,v){
  $('input'+inputTextIDs[i][0]).val(inputTextIDs[i][1]);
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="hotelLocaiton" />
<input type="text" id="agentTransfersSearchForm_filter_transfersName" />

Since it's a 2 dimensional array, where as you are providing only 1 dimension as i.

To access 2D array, you need to do something like inputTextID[i][0]

Upvotes: 1

Related Questions