0

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_box_tag(:fenix_fee_no_charged) %>
<%= label_tag(:fenix_fee_no_charged, "FENIX_FEE_NO_CHARGED") %>

I created the javascript to set one or another:

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

When my options to check increased, I decided to create the checkbox dynamically:

<% Enums::FlightEnum::FENIX_FLIGHTS_NOTIFICATIONS.each do |notification, value| %>
  <%= check_box_tag notification, value %>
  <%= label_tag notification, notification.to_s.upcase, :class => "checkbox inline" %>
<% end %>

When I checked the javascript function, this did not work. I would appreciate any help that you can give me!

James Chevalier
  • 10,604
  • 5
  • 48
  • 74
nisevi
  • 627
  • 1
  • 10
  • 27
  • Use [event delegation](http://stackoverflow.com/questions/18414695/attaching-events-after-dom-manipulation-using-jquery-ajax). – Blazemonger Oct 21 '13 at 14:29
  • Is there any js error. try to print something using 'console.log' in click function? – userxyz Oct 21 '13 at 14:29

2 Answers2

2

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"); 
})
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

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);
palaѕн
  • 72,112
  • 17
  • 116
  • 136