I am using MVC3 and Entity Framework. I have a List on a page with checkboxes for the user to select multiple items. (The goal is to “Reassign” multiples at a time).
When the user clicks the “Reassign” buttion it invokes a JQuery Dialog box to appear and it loads the partial view. On the partial view, I have a hidden field for the checkboxes that were selected.
An example would be:
<input type="hidden" value="2,4,5" class="tasks" name="tasks" />
However, my code runs too fast for the JQuery to grab which checkboxes were checked. When I view the Dialog box HTML in Firebug, the value is empty.
I have tested my code out by doing:
var checkeditems = $('input:checkbox[name="selectedObjects"]:checked').map(function () { return $(this).val() }).get().join(",");
alert(checkeditems);
$('input.tasks').val(checkeditems);
Weirdly, the values are put into the hidden field. Without the alert, they are not there.
Here is my Javascript:
$('#ReAssign').bind('click', function (event, ui) {
GetReassign();
return false;
});
function GetReassign() {
$("#ReassignDialog").dialog({
height: 315,
width: 525,
modal: true,
draggable: false,
resizable: false,
open: function (event, ui) {
$(this).load('/InterviewFollowup/ReassignPartial');
},
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
var checkeditems = $('input:checkbox[name="selectedObjects"]:checked').map(function () { return $(this).val() }).get().join(",");
$('input.tasks').val(checkeditems);
}
Here is my View:
@using (Html.BeginForm("ReassignPost","InterviewFollowup")) {
<fieldset>
<legend><strong>Re-Assign Task</strong></legend>
<input type="hidden" value="" id="tasks" class="tasks" name="tasks" />
<div class="editor-label">
Location:
</div>
<div class="editor-field">
@Html.DropDownList("MailCodes", (SelectList)ViewBag.MailCodes,"-- Select --")
@Html.ValidationMessage("MailCodes")
</div>
<br />
<div class="editor-label">
@Html.LabelFor(model => model.AssignedTo)
</div>
<div class="editor-field">
<select name="AssignedTo" id="AssignedTo"></select>
</div>
<div class="editor-label">
Notes:
</div>
<div class="editor-field">
<input type="text" name="Notes" id="Notes" />
@Html.ValidationMessage("Notes")
</div>
<p>
<input type="submit" value="Submit" />
<input type="button" value="Cancel" />
</p>
</fieldset>
}
The
.load()jQuery function is asynchronous (it’s an AJAX call), so this code:is run before the partial view has been loaded, and therefore your
$('input.tasks')selector doesn’t match an element – adding the alert fixes this because it delays execution of the next line until after the AJAX call has completed. You’ll want to move that code into a callback function for when the.load()has completed, like so: