Reputation: 255
I have a process that needs to use dynamically added objects. How do I access these objects in Jquery.
Current: Not displaying the two div tags '#transferorProfileGroups' and '#transfereeProfile' When the transtypesvalue is equal to "transfer in" or "transfer out".
Results I want: To display or hide these div tags when conditions are met.
var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string")
obj = '"' + obj + '"';
return String(obj);
} else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n];
t = typeof (v);
if (t == "string")
v = '"' + v + '"';
else if (t == "object" && v !== null)
v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));R
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
$(document).ready(function () {
setJobExceptionDataTable();
handleTransferTypeSelection();
});
function handleTransferTypeSelection() {
$('#tranTypes').live('change' , function () {
alert("help")
var transfertypesvalue = $(this).val();
if (transfertypesvalue == "Transfer In") {
$('#transferorProfileGroups]').removeClass('invisible');
$('#transfereeProfile').addClass('invisible');
}
else if (transfertypesvalue == "Transfer Out") {
$('#transfereeProfile').removeClass('invisible');
$('#transferorProfileGroups').addClass('invisible');
}
else {
$('#transfereeProfile').addClass('invisible');
$('#transferorProfileGroups').addClass('invisible');
}
});
}
function getJobExceptionDetails(jobId, jobName, jobStatus, jobSubmitted, jobExceptionType) {
var getDetailsUrl = '';
var setTables = '';
switch (jobExceptionType) {
case "ProfileSelectionRequired":
setTables = setProfileSelectionRequiredDataTables;
getDetailsUrl = "/JobException/GetProfileSelectionRequiredDetails";
break;
default:
alert('JobExceptionType not defined. (' + jobExceptionType + ')');
return false;
break;
}
$.ajax({
url: getDetailsUrl,
type: "GET",
data: {
JobId: jobId,
JobStatus: jobStatus,
JobSubmitted: jobSubmitted,
JobName: jobName,
JobExceptionType: jobExceptionType
},
beforeSend: function () {
$('#loading').show();
},
success: function (result) {
$(".detailsModalContent").append(result);
setTables();
$("#detailsModal").modal({
autoResize: true,
autoPostition: true,
closeHTML: "",
dataCss: {
padding: "10px"
},
minHeight: 350,
maxHeight: 700,
minWidth: 900,
maxWidth: 900,
overlayClose: true
});
$("#btnResolveProfileSelectionRequired").click(function () {
handleResolveProfileSelectionRequired();
});
$('.datepicker').datepicker();
$('input[type=checkbox][name=profilegroup]').change(function () {
checked = $(this).attr('checked');
if (checked) {
$('input[type=checkbox][name=profilegroup]').removeAttr('checked');
$(this).attr('checked', 'checked');
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Failed to retrieve items, please try again.');
},
complete: function () {
$('#loading').hide();
}
});
}
function handleResolveProfileSelectionRequired() {
var valid = true;
var msg = '';
var notEmpty = /\S/
var transferEffectiveDate = $("#TransferEffectiveDate").val();
if (!notEmpty.test(transferEffectiveDate)) {
msg += "Please select a transfer effective date.\r\n";
valid = false;
}
var selectedGroup = $("select[name='profileGroups']").val();
if (selectedGroup == undefined || selectedGroup <= 0) {
msg += "Please select a transferor profile group.\r\n";
}
if (!valid) {
alert(msg);
} else {
$.ajax({
url: "/JobException/ResolveProfileSelectionRequired/",
dataType: "json",
traditional: true,
type: "POST",
data: {
__RequestVerificationToken: $('input[name=__RequestVerificationToken]').val(),
JobId: $("#JobException_JobId").val(),
TransferEffectiveDate: transferEffectiveDate,
SelectedTransferorProfileGroupId: selectedGroup
},
beforeSend: function () {
$('#loading').show();
},
success: function (result) {
window.location.reload();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Failed to resolve profile selection required job exception, please try again.');
window.location.reload();
},
complete: function () {
$('#loading').hide();
}
});
}
}
function setJobExceptionDataTable() {
aoColumnsObject =
[
{
"sName": "JobId",
"sType": "numeric",
"fnRender": function (oObj) {
var jobId = oObj.aData[0];
var jobName = oObj.aData[1];
var jobSubmitted = oObj.aData[2];
var jobStatus = oObj.aData[3];
return '<a href="/" class="detailsLink"' + '" jobid="' + jobId + '" jobname="' + jobName + '" jobstatus="' + jobStatus + '" jobsubmitted="' + jobSubmitted + '">' + jobId + "</a>";
}
},
{ "sName": "JobName" },
{ "sName": "JobSubmitted", "sType": "date" },
{ "sName": "JobStatus" }
];
var oTable = $("#orderQueueTable").dataTable({
"bServerSide": true,
"sAjaxSource": "/JobException/GetJobExceptionItems/",
"bProcessing": false,
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "jobExceptionType", "value": $("#JobExceptionType").val() });
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"beforeSend": function () {
$("#loading").removeClass('invisible');
},
"success": fnCallback,
"complete": function () {
$(".detailsLink").live('click', function () {
getJobExceptionDetails($(this).attr('jobid'), $(this).attr('jobname'), $(this).attr('jobstatus'), $(this).attr('jobsubmitted'), $("#JobExceptionType").val());
return false;
});
$("#loading").addClass('invisible');
}
});
},
"aoColumns": aoColumnsObject,
"iDisplayLength": 25,
"bDestroy": true,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bAutoWidth": false
});
}
function setProfileSelectionRequiredDataTables() {
$("#orderInfoTable").dataTable({
"bJQueryUI": true,
"bAutoWidth": false,
"bDestroy": true,
"bSort": false,
"bPaginate": false,
"bFilter": false,
"bInfo": false,
"aoColumns": [
null,
null,
{ "sType": "date" },
null
]
});
}
and here is the html:
@model MarylinMonroeMvcSite.Models.JobException.ProfileSelectionRequiredModel
<div class="float-left">Profile Selection Required Resolution</div>
<div class="float-right">Job Id: @Model.JobException.JobId</div>
<div class="clear"></div>
<br />
<form method="post" target="/JobException/ResolveProfileSelectionRequired" id="profileSelectionResolutionForm">
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.JobException.JobId, new { value = Model.JobException.JobId })
<div>
Job Id: @Model.JobException.JobId<br />
Job Name: @Model.JobException.JobName<br />
Job Submitted: @if (Model.JobException.JobSubmitted.HasValue)
{ @Model.JobException.JobSubmitted.Value.ToString("MM/dd/yyyy HH:mm:ss") }<br />
Job Status: @Model.JobException.JobStatus
</div>
<br />
<div id="transferTypes">
Select Transfer Type:
<select name="tranTypes" id="tranTypes">
<option value="0">Please Choose Transfer Type</option>
@foreach (var type in Model.TransferTypes)
{
<option value="@type.TypeId">@type.TypeDescription</option>
}
</select>
</div>
<br />
<div>
Transfer Effective Date:
@Html.TextBoxFor(x => x.TransferEffectiveDate, new { @class = "datepicker" })
</div>
<br />
<div id="transferorProfileGroups" class="invisible">
Select Transferor Profile Group<br />
<select name="profileGroups">
<option value="0">Please Choose Group</option>
@foreach (var group in Model.TransferorProfileGroups)
{
<option value="@group.GroupId">@group.DisplayName</option>
}
</select>
</div>
<div id="transfereeProfile" class="invisible">
Select Transferee Profile Group <br />
<select name="transfereeGroups">
<option value="0">Please Choose Group</option>
@foreach (var feree in Model.TransfereeList)
{
<option value="@feree.TransfereeListId">@feree.TransfereeName</option>
}
</select>
</div>
<br />
<div>
<input type="button" value="Submit" id="btnResolveProfileSelectionRequired" />
</div>
</form>
Upvotes: 1
Views: 412
Reputation: 255
I fixed the problem was a little thing that I wasn't seeing. Since I could not use .on due to using an older version of Jquery I stuck with .live which worked fine. I just had my if statement searching for values instead of the labels. So the code went from:
function handleTransferTypeSelection() {
$('#tranTypes').live('change' , function () {
var transfertypesvalue = $(this).val();
if (transfertypesvalue == "Transfer In") {
$('#transferorProfileGroups]').removeClass('invisible');
$('#transfereeProfile').addClass('invisible');
}
else if (transfertypesvalue == "Transfer Out") {
$('#transfereeProfile').removeClass('invisible');
$('#transferorProfileGroups').addClass('invisible');
}
else {
$('#transfereeProfile').addClass('invisible');
$('#transferorProfileGroups').addClass('invisible');
}
});
}
and is now:
function handleTransferTypeSelection() {
$('#tranTypes').live('change' , function () {
var transfertypesvalue = $('#tranTypes option:selected').text();
// ^ ^ ^ ^ ^ ^ ^ ^ ^ the changes
if (transfertypesvalue == "Transfer In") {
$('#transferorProfileGroups]').removeClass('invisible');
$('#transfereeProfile').addClass('invisible');
}
else if (transfertypesvalue == "Transfer Out") {
$('#transfereeProfile').removeClass('invisible');
$('#transferorProfileGroups').addClass('invisible');
}
else {
$('#transfereeProfile').addClass('invisible');
$('#transferorProfileGroups').addClass('invisible');
}
});
}
little things make all the difference.
Upvotes: 0
Reputation: 16616
jQuery bindings like "live", "click" will bind to elements when the DOM finish its loading. Any elements that are AJAX response wont be bound to them. Instead you should use the ".on" method.
Like this:
$(document).on('click', '.my_new_element', function() {
//your code here
});
That will work because ".on" is bound to the document and not a specific element. And since the 2nd parameter ('#my_new_element') is a filter the click event will only fire this function when performed on that element.
So as long as new HTML elements come via AJAX with that 'my_new_element' class on it they will fire your function when the event is performed on them.
Just for clarification: you don't need to bind to the "document". You could bind the ".on" method into any element that is guaranteed loaded before the AJAX is called. For example all your site is inside a <div class="content"></div>
in this case you could bind like this:
$('.content').on('click', '.my_new_element', function() {
//your code here
});
Upvotes: 1