jquery将事件绑定到复选框数组中的一个复选框

时间:2022-01-08 08:58:49

I have a dynamic group of checkboxes pr_network_ids that is a HABTM relationship in RAILS. So they each have the same name, but different values

我有一组动态的复选框pr_network_ids,这是RAILS中的HABTM关系。所以它们每个都有相同的名称,但值不同

I want to toggle a div to be shown or hidden when pr_network_ids_2 and pr_network_ids_4 is clicked/unclicked.

我想在单击/取消单击pr_network_ids_2和pr_network_ids_4时切换要显示或隐藏的div。

Using JQuery i have tried to access it using ("#pr_network_ids_2").click, but i can't get it to work. Is there a way to access a specific checkbox using the id or name or get the entire array of checkboxes and bind an event to the ones if there value equals 2 or 4?

使用JQuery我试图使用(“#pr_network_ids_2”)来访问它。点击,但我无法让它工作。有没有办法使用id或名称访问特定的复选框或获取整个复选框数组并将事件绑定到那些值,如果值等于2或4?

3 个解决方案

#1


1  

Try this

尝试这个

$("input:checkbox[name=nameOfTheCheckbox]").each(function(){
       var $this = $(this);
 if($this.val() == "2" || $this.val() == "4"){
  //bind the events here
  $this.bind("click", function(){ });
 }
});

#2


0  

If you use $("#pr_network_ids_2") you have to find the checkbox, if you have defined the checkbox with that id.

如果您使用$(“#pr_network_ids_2”),则必须找到该复选框,如果您已使用该ID定义了复选框。

example

<input type="checkbox" id="pr_network_ids_2" value="lalala" />

Make sure Your checkbox has the correct ID.

确保您的复选框具有正确的ID。

#3


0  

("#pr_network_ids_2").click(...) should work. But if they are dynamic, you either need to do the binding after they are created or use .live()

(“#pr_network_ids_2”)。点击(...)应该有效。但如果它们是动态的,您需要在创建后使用绑定或使用.live()

#1


1  

Try this

尝试这个

$("input:checkbox[name=nameOfTheCheckbox]").each(function(){
       var $this = $(this);
 if($this.val() == "2" || $this.val() == "4"){
  //bind the events here
  $this.bind("click", function(){ });
 }
});

#2


0  

If you use $("#pr_network_ids_2") you have to find the checkbox, if you have defined the checkbox with that id.

如果您使用$(“#pr_network_ids_2”),则必须找到该复选框,如果您已使用该ID定义了复选框。

example

<input type="checkbox" id="pr_network_ids_2" value="lalala" />

Make sure Your checkbox has the correct ID.

确保您的复选框具有正确的ID。

#3


0  

("#pr_network_ids_2").click(...) should work. But if they are dynamic, you either need to do the binding after they are created or use .live()

(“#pr_network_ids_2”)。点击(...)应该有效。但如果它们是动态的,您需要在创建后使用绑定或使用.live()