user3089927
user3089927

Reputation: 3905

Populate divs based on some value of div

I have a webpage with multiple divs getting created and populated in forloop (wsgi-python). My javascript is changing only first div and not processing further. How to make it happen on all the divs on the webpage?

https://jsbin.com/taximawino/edit?html,output

Upvotes: 0

Views: 137

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

id should be unique , so you can use class instead if multiple elements need to be select, then use data-value attribute instead of value attribute, since it's the proper way to add custom attribute and you can access it using data('value'). Then you can iterate over jQuery selected element using each() and select previous element using prev()

$(document).ready(function() {
  // var mb = $('#state').text();
  $('.state').each(function() {
    var mb = $(this).data('value');
    if (mb == 1) {
      $(this).prev().addClass("circleb");
    } else if (mb == 2) {
      $(this).prev().addClass("circlec");
    }
  });
});
div.circlea {
  background-color: #d0e4fe;
  width: 15px;
  height: 15px;
  -webkit-border-radius: 15px;
  -moz-border-radius: 15px;
  border-radius: 15px;
}
div.circleb {
  background-color: #66FF99;
  width: 15px;
  height: 15px;
  -webkit-border-radius: 15px;
  -moz-border-radius: 15px;
  border-radius: 15px;
}
div.circlec {
  background-color: #FFCCCC;
  width: 15px;
  height: 15px;
  -webkit-border-radius: 15px;
  -moz-border-radius: 15px;
  border-radius: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="demo" class="circlea"></div>
  <div class="state" data-value="1"></div>
</div>
<div>
  <div class="demo" class="circlea"></div>
  <div class="state" data-value="2"></div>
</div>

Upvotes: 1

Related Questions