2

I'm trying to give each td with the class '.m' a value from the array.

i.e. the first cell is given first number from the array, the second cell is given the second number etc.

The problem is that all of the cells are being given the same value of '1'

Any help is much appreciated.

Here is what I've tried so far:

JsFiddle: https://jsfiddle.net/Fraser_M/8cs5tcav/2/

HTML:

<table>
 <tr>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
 </tr>
 <tr>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
  <td class='m'></td>
 </tr>
</table>

JS:

$(function() {

 var myArray = [1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1];
 var myArrayLength = myArray.length;


 for (var i = 0; i < myArrayLength; i++) {
   $('.m').text(myArray[i]);
 }

});

2 Answers 2

2

The problem is that $('.m') selects all of the elements with every iteration, so they'll all be set to the last element in the array.

I think this is what you were going for: https://jsfiddle.net/z9t4w7s3/1/

EDIT: code block from the fiddle:

$(function() {
  var myArray = [1,0,0,1,0,0,1,0,1,0,1,1];
  var myArrayLength = myArray.length;
  $('.m').each(function(i, element) {
    $(element).html(myArray[i]);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use .eq() to select element at index i within .m collection of elements within for loop

$(function() {
 // cache selector
 var m = $(".m");

 var myArray = [1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1];
 var myArrayLength = myArray.length;

 for (var i = 0; i < myArrayLength; i++) {
   m.eq(i).text(myArray[i]);
 }

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.