Skip to content Skip to sidebar Skip to footer

I Can't Access The Keys Of Checkbox With Javascript When I Generate The Checkbox Dynamically

I created a checkbox in my html.erb as the following: <%= check_box_tag(:fenix_fee_charged) %> <%= label_tag(:fenix_fee_charged, 'FENIX_FEE_CHARGED') %> <%= check_b

Solution 1:

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on('click', '#fenix_fee_charged', function(event) {
    $('#fenix_fee_no_charged').removeAttr("checked"); 
})

Solution 2:

Since the checkbox are added dynamically, you need to use event delegation to register the event handler

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on('click', '#fenix_fee_charged', function(event) {
    $('#fenix_fee_no_charged').removeAttr("checked"); 
});

$(document).on('click', '#fenix_fee_no_charged', function(event) {
    $('#fenix_fee_charged').removeAttr("checked"); 
});

EDIT

Also try to use .prop() method like:

// Uncheck the checkbox
$('#fenix_fee_no_charged').prop("checked", false);

// Check the checkbox
$('#fenix_fee_no_charged').prop("checked", true);

Post a Comment for "I Can't Access The Keys Of Checkbox With Javascript When I Generate The Checkbox Dynamically"