Using JQuery with dynamically added controls (MVC)
I have a set of radio buttons that are dynamically generated (via JSON call):
StringBuilder sbEligAll = new StringBuilder();
sbEligAll.Append("<div id='currentselectiondepartment'>");
sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radCurrent' value='0' /><label for='radCurrent'>Current</label>");
sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radFuture' value='1' /><label for='radFuture'>Future</label>");
sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radCurrentAll' value='2' /><label for='radCurrentAll'>Current All</label>");
sbEligAll.Append(" <input type='radio' name='selectalldepartment' id='radFutureAll' value='3' /><label for='radFutureAll'>Future All</label>");
sbEligAll.Append("</div>");
Then:
return Json(new { TableList = sbElig.ToString() }, JsonRequestBehavior.AllowGet);
Is there a way to get jQuery to be able to interact with these?
For example:
$("input[name=selectalldepartment]").change(function() {
var str = $('input[name=selectalldepartment]:checked').val();
$(".radiolist[value='" + str + "']").attr("checked", true);
});
I've tried everything I know how to do, but the jQuery just doesnt fire. (I've added alerts to the jQuery code to see if it actually gets called, and it d开发者_JAVA百科oes not).
Any thoughts?!
Thanks!
Use .live()
like this:
$("input[name=selectalldepartment]").live('change', function() {
var str = $('input[name=selectalldepartment]:checked').val();
$(".radiolist[value='" + str + "']").attr("checked", true);
});
When you run your current code it looks for that selector, and attaches an event handler to those elements...the new elements weren't there to attach to when it was run. The other option is when you're adding the controls, add the handler there to the new ones matching the same selector in the response, something like this:
$.ajax({
url: blah.aspx...
success: function(data) {
//do stuff
$("input[name=selectalldepartment]", data).change(function() {
//Code or a function to keep it tidy
});
}
});
精彩评论