简体   繁体   中英

change label foreach element in html using javascript

I am using both html and velocity and came up with this code. The names and images are stored in an array and this is the code I used to display each of the contents of this array to the page.

#foreach($starter in $starter)
    <div class="product">  
      <div class="color"><img src= "$starter.img" width="100" height="100"></div>
      <span class="product-name">$starter.name</span>
      <div class="compare-wrap">
        <input type="checkbox" id="">
        <label id="view">Compare</label>
      </div>
    </div>
  #end

I wanted the label to change from "Compare" to "View Compare" while at the same time storing its id in the array upon checking their correspondng check box. I eventually came up with this code:

var checkedArray = [];

$(":checkbox").change(function(){
  if((this).checked){
    checkedArray.push(this.id);
    document.getElementById('view').innerHTML = "<a href='/compare'>View Compare</a>";
  }
  else{
    checkedArray.splice(checkedArray.indexOf(this.id), 1);
    document.getElementById('view').innerHTML = 'Compare';
  }
var str = checkedArray.join(', ');
alert(str);
});

but it seems it is only applicable to the first content of the array. Any idea how I can use a foreach code at this point?

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You should use a class:

var views = document.getElementsByClassName('view');

var  i = views.length; 

while(i--) { 

      views[i].innerHTML = "Compare";
}

HTML

 <label class="view">Compare</label>

Element ID must be unique.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM