Uzma Khan Uzma Khan - 4 months ago 11
HTML Question

for in loop affecting only last element of array,I want my code to work on each element of array

I am trying to change html of each class that is contained in my array. But for(var i in array) loop only processing the last array element.How to make it work for each element of array.Here is my code:

$(document).ready(function(){
var a=[],array=[".1",".2",".3",".4",".5",".6",".7",".8",".9"];
// a.push($(array[i]).html());
for(var i in array){
$(array[i]).click(function(){
$(array[i]).html(0);
});
}
});


See the problem here http://codepen.io/meow414/pen/rLJaPJ (its code may change as I will be trying to solve it). HTML code is here :

<div class="container-fluid">
<div class="row">
<div class="col-xs-8 col-md-10">
<div class="row">
<div class="1 col-xs-4 col-md-4">1
</div>
<div class="2 col-xs-4 col-md-4">2
</div>
<div class="3 col-xs-4 col-md-4">3
</div>
</div>
<div class="row">
<div class="4 col-xs-4 col-md-4">4
</div>
<div class="5 col-xs-4 col-md-4">5
</div>
<div class="6 col-xs-4 col-md-4">6
</div>
</div>
<div class="row">
<div class="7 col-xs-4 col-md-4">7
</div>
<div class="8 col-xs-4 col-md-4">8
</div>
<div class="9 col-xs-4 col-md-4">9
</div>
</div>
</div>
</div>
</div>

Answer

Remove the for loop and crate a selector from your array using join()

jQuery(function( $ ){

  var array=[".1",".2",".3",".4",".5",".6",".7",".8",".9"];

  $(array.join(",")).click(function(){
     $(this).html("Hello");
  });

});

Currently you have an array

[".1",".2",".3",".4",".5",".6",".7",".8",".9"]  

but you need a selector

".1,.2,.3,.4,.5,.6,.7,.8,.9"

therefore use .join(",")

jQuery(function( $ ){
  
  var array=[".1",".2",".3",".4",".5",".6",".7",".8",".9"];


  $(array.join(",")).click(function(){
     $(this).html("Hello");
  });

  
});
[class^=col-]{background:#eee;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="col-xs-8 col-md-10">
      <div class="row">
        <div class="1 col-xs-4 col-md-4">1
        </div>
        <div class="2 col-xs-4 col-md-4">2
        </div>
        <div class="3 col-xs-4 col-md-4">3
        </div>
      </div>
      <div class="row">
        <div class="4 col-xs-4 col-md-4">4
        </div>
        <div class="5 col-xs-4 col-md-4">5
        </div>
        <div class="6 col-xs-4 col-md-4">6
        </div>
      </div>
      <div class="row">
        <div class="7 col-xs-4 col-md-4">7
        </div>
        <div class="8 col-xs-4 col-md-4">8
        </div>
        <div class="9 col-xs-4 col-md-4">9
        </div>
      </div>
    </div>
  </div>
</div>

Also note that using Number as class is invalid. Will work in JS bul will fail in CSS. (P.S: ID as Number on the other hand is valid in HTML5)

Comments