dongyi1777
2017-07-19 04:45
浏览 660
已采纳

如何从ajax加载的内容中获取复选框值

I have external file which generate the checkbox list. And this file was load through jquery load. I want the checkbox click and update its parent div with something.

html

<div id="testiContent"></div>

checkbox.php

<div class="alert alert-info"><input type='checkbox' class='groupid' value='1'>1</div>
<div class="alert alert-info"><input type='checkbox' class='groupid' value='2'>2</div>
<div class="alert alert-info"><input type='checkbox' class='groupid' value='3'>3</div>

jquery

$('#testiContent').load('checkbox.php');//load file via ajax
$("#testiContent input.groupid").change(function(){
    if($(this).is(":checked")){
        $(this).parents().addClass("alert alert-success"); 
    }else{
        $(this).parent().removeClass("alert alert-success");  
    }
});

Ideally, when the checkbox click, then the alert div will change into green. I can make it working on the normal scrip but not a chance with ajax.

Fiddle here : http://jsfiddle.net/o6Lk17db/1/

图片转代码服务由CSDN问答提供 功能建议

我有外部文件生成复选框列表。 这个文件是通过jquery加载加载的。 我希望复选框单击并更新其父div。

html

 &lt; div id  = “testiContent” &GT;&LT; / DIV&GT; 
   
 
 

<强> checkbox.php

 <  code>&lt; div class =“alert alert-info”&gt;&lt; input type ='checkbox'class ='groupid'value ='1'&gt; 1&lt; / div&gt; 
&lt; div class =“alert alert-  info“&gt;&lt; input type ='checkbox'class ='groupid'value ='2'&gt; 2&lt; / div&gt; 
&lt; div class =”alert alert-info“&gt;&lt; input type ='复选框 'class ='groupid'value ='3'&gt; 3&lt; / div&gt; 
   
 
 

jquery \ n

  $('#testiContent')。load('checkbox.php'); //通过ajax加载文件
 $(“#testiContent input.groupid”)。change(function(){\  n if($(this).is(“:checked”)){
 $(this).parents()。addClass(“alert alert-success”); 
} else {
 $(this)。  parent()。removeClass(“alert alert-success”); 
} 
}); 
   
 
 

理想情况下,当复选框单击时,则警告div 将变成格力 ñ。 我可以使用正常的脚本而不是ajax的机会。

在这里小提琴: http://jsfiddle.net/o6Lk17db/1/

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douman6245 2017-07-19 04:55
    已采纳

    You can't bind to an element that isn't there yet, so your dynamically added ones aren't subject to the $"#testiContent input.groupid" selector. The way around this is to bind to something that is already present. For example, the parent container where your elements are dynamically being added.

    Try something like this:

    $("#testiContent").on('change', 'input', function(){ ... });
    

    will attach a listener to the parent, specifically for events on the appropriate (input) targets within that parent.

    评论
    解决 无用
    打赏 举报
查看更多回答(4条)

相关推荐 更多相似问题