1

first thanks for your help in advance. I'm pretty newbie in jquery and javascript and I don't speak so much english so i cound't found nothing liked in my research.

This is my html

<li></li>
<li></li>
<li id="user1"></li>
<input type="checkbox" id="checkbox1">

<li></li>
<li></li>
<li id="user2"></li>
<input type="checkbox" id="checkbox2">

I want to everytime that a checkbox with id ("checkbox"+i) is checked I toggle a class in the ("user"+i) to push in a list and then send with post request.

I tryed this

for(i = 1; i < 3; i++) {    
   document.getElementById('checkbox' + i).addEventListener('change', function() {
        document.getElementById('user' + i).setAttribute("class", "passInterestIds");
  });
} 

but it only gives me user3 independent of the checkbox

How can I Make this work?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73

1 Answers1

0

So this will always work as long as the id contains ONE digit cause that what we're taking from the match function. Then if checkbox gets checked add class hello else remove class hello

var elements = $('input[type^=checkbox');
elements.on('click', function(){
  var idNr = $(this).attr('id').match(/\d+/)[0];
  if($(this).is(':checked')) {
    $('#user' + idNr).addClass('hello');
  } else {
    $('#user' + idNr).removeClass('hello');
  }
});
.hello {
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li id="user1"></li>
<input type="checkbox" id="checkbox1">

<li id="user2"></li>
<input type="checkbox" id="checkbox2">

If possible to change the HTML.. The better way would be to use the value attribute from the input element containing the number. Or use a data-user-id attribute if you can not use the value attribute.

var elements = $('input[type^=checkbox');
elements.on('click', function(){
  var idNr = $(this).val();
  if($(this).is(':checked')) {
    $('#user' + idNr).addClass('hello');
  } else {
    $('#user' + idNr).removeClass('hello');
  }
});
.hello {
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li id="user1"></li>
<input type="checkbox" id="checkbox1" value="1">

<li id="user2"></li>
<input type="checkbox" id="checkbox2"  value="2">
caramba
  • 21,963
  • 19
  • 86
  • 127