Reputation: 1181
I have checkboxes in my checkbox list like following:
<div class="pop-mission-to">
<label>
<input class="check-brand" type="checkbox" name="" value="1" data-id="1">
</label>
</div>
<div class="pop-mission-to">
<label>
<input class="check-brand" type="checkbox" name="" value="2" data-id="2">
</label>
</div>
I have created a on click function in jQuery like this, just to check if its gonna react or anything:
$('.check-brand').click(function() {
alert("Checkbox checked");
});
However when I click the checkbox nothing happens. What am I doing wrong?
Edit, guys I'm creating this HTML after $.Post like following:
$('.check-user').click(function() {
var $this = $(this);
var user_id = $this.attr('value');
var brandContainer = $this.closest('.pop-state').siblings('.pop-brands');
brandContainer.html('<p style="margin: 10px !important;">Processing... </p>');
$.post('/user/usersBrands', { userId: user_id } , function(data) {
console.log(data);
var brands = JSON.parse(data);
var container = $('<div class="pop-mission-co" />');
brands.forEach(function (brand, index) {
var isRegisteredToBrand = null;
console.log(brand.userId);
if(brand.userId==null)
{
isRegisteredToBrand = false;
}
else{
isRegisteredToBrand = true;
}
console.log(isRegisteredToBrand);
container.append(buildBrand(brand.id, brand.name, isRegisteredToBrand, index));
});
function buildBrand(id, name, isActive, index) {
var isChecked = isActive ? 'checked="checked"' : ' ';
return $(
'<div class="pop-mission-to">' +
'<label>' +
'<input class="check-brand"' +
isChecked +
'type="checkbox"' +
'name=""' +
'value="' + id + '"' +
'data-id="' + index + '">'
+ name +
'</label>' +
'</div>'
);
}
brandContainer
.children('p').remove();
brandContainer
.html(container)
.find('.pop-mission-co').show();
});
});
Perhaps the fact because the HTML is generated after $.post call in jquery, that's the reason why it doesn't triggers the event??
Upvotes: 0
Views: 1746
Reputation: 337560
The issue is because you are appending the element dynamically after the DOM has been loaded, so you need to use a delegated event handler. Also note that you should use the change
event on checkboxes, not click
. Try this:
$('.check-user').click(function() {
var $this = $(this);
var user_id = $this.attr('value');
var brandContainer = $this.closest('.pop-state').siblings('.pop-brands');
brandContainer.on('change', '.check-brand', function() {
alert("Checkbox checked");
});
// the rest of your code...
});
Upvotes: 2