I can't access the keys of checkbox with javas

2019-09-08 14:53发布

问题:

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!

回答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);


回答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"); 
})