0

Hi i want to select the div with a Class that have same name as my $id variable.

Everything is working if i add the div id by myself but i want it to be based on my $id variable.

Is this possible or is there a better way to target the right div based on the button that was clicked?

$('.checkbox-group').find('input[value=button]').click(function() { //find all buttons with value=button

var $toggle = $(this); 
//add buttons in variable $toggle

var $id = $( this ).attr('id');                                     
//add the clicked button´s ID in the variable $id

if ($toggle.prop('checked') === true) {                             
//if the clicked button is checked 

$('#my-grp div.$id').removeClass('kill');                       
//want to select the div with Class that have same name as my $id variable

} else {
//and then add or remove the class .kill

$('#my-grp div.$id').addClass('kill');                          
}
});
  • 1
    Include some sample HTML so we can see what your code is trying to do. – Keith Feb 22 '14 at 20:27
  • This is JavaScript not PHP. You don't need `$` before your var and it doesn't see your variable in the string. You need to concatenate, like in the answer. – Bill Feb 22 '14 at 20:31

3 Answers3

1

The solution is just a simple string concatenation away :)

$('#my-grp div.' + $id).removeClass('kill');
Andreas
  • 21,535
  • 7
  • 47
  • 56
0

jQuery won't process variables in string quotes, you should concatenate it.

Instead of this:

$('#my-grp div.$id').removeClass('kill');

write this:

$('#my-grp div.' + $id).removeClass('kill');

EDIT: Oops, it looks someone was faster :)

KristofMorva
  • 639
  • 1
  • 7
  • 13
0

You can concat string and variables. In your case something like this:

$('#my-grp div.' + $id ).removeClass('kill');

Side note: Variables in javascript doesn't need a $. In you case id would be a better variable name to store a string.

$ is normally used to store jquery elements, like $toggle.

jaapaurelio
  • 274
  • 4
  • 16