Dynamically adding dijit on button click programatically...how? - javascript

I've got a problem with another dojo enabled form that I am working on. A user can enter details onto the page by entering the data using a dialog box, which in turn updates the database and then displays the user data entered on to the form.
Each element added consist of 2 x Validation Text boxes 1 x FilteringSelect. When it's added to the page they are added as simply text boxes.
I've tried just adding as standard strings but that means the dojo.parse() does not run on the code. I've also tried programmatically adding the elements but that just displays the element object as a string to the page. So far I have:
var xhrArgs = {
url: url,
handleAs: "text",
preventCache: true,
load: function(data){
var idResult = parseInt(data);
if(idResult > 0){
var divStr = '<div id="employ_' + idResult + '" style="float:left;width:100%;">' +
'<table width="300">' +
'<tr>' +
'<td height="29"><Strong>' +
'<input type="text" dojoType="dijit.form.ValidationTextBox ' +
'change="markEmploymentForUpdate(); ' +
'id="cmpy_'+ idResult +'" '+
'required="true" ' +
'promptMessage="Please enter a valid company name" ' +
'invalidMessage="please enter a valid company name" ' +
'trim="true"' +
'value="'+ companyname +'"/>' +
'</td>' +
'<td height="29"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" onchange="markEmploymentForUpdate();" id="roleInput_'+ idResult +'" value="'+ jobrole +'" ></td>' +
'<td height="29">' +
'<input type="text" dojoType="dijit.form.ValidationTextBox" onchange="markEmploymentForUpdate();"' +
'id="jtitle_'+ idResult + '"' +
'required="true"' +
'promptMessage="Please enter your job title"' +
'invalidMessage="Please enter your job title"' +
'value="'+ jobtitle + '"/>' +
'</td>' +
'<td height="29"><img src="/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor=\'pointer\';" onclick="removeEmployer(\'employ_'+ idResult +'\', '+ idResult +')" /></td>' +
'</tr>' +
'</table>' +
'</div>';
dijit.byId('companydetails').hide();
dijit.byId('employername').setValue('');
dijit.byId('jobtitle').setValue('');
dijit.byId('jobrole').setValue('');
dojo.byId('data-table').innerHTML += divStr;
dojo.byId('companydetails').hide();
}else{
dojo.byId('add-error').innerHTML = '<div class="error">Unable to process your request. Please try again.</div>';
}
}
};
var deferred = dojo.xhrGet(xhrArgs);
This is displaying text boxes as the dojo.parse isn't running on this. If I replace the ValidationTextBox with:
var textbox = new dijit.form.ValidationTextBox({
id:"cmpy_" + idResult,
required:true,
trim:true,
"change":"markEmploymentForUpdate();",
promptMessage:"Please enter a valid company name",
value:companyname
});
I just get the object printed to the page.
Any ideas how I can added this to my page and maintain the dojo component rather than it defaulting to a text box?
Many thanks.

dojo.parser.parse(dojo.byId('data-table')); after you set it's innerHTML

Related

jQuery: selected dropdown option returning undefined

I have a functionality where in a table, I can click an add button and a new tr gets prepended to the table. However, I want field AddOn to get disabled if a certain food category is selected. It is easy to tackle it on change but how to do it when I click on add and depending on the value originally selected in dropdown?
var index = 0;
var FoodCategory = "FoodCategory" + index;
var tr = '<tr class="row">' +
'<td></td>' +
'<td></td>' +
'<td><select id="' + FoodCategory + '" type="text" class="form-control" /><span id="FoodCat""></select></span></td>' +
'<td><span><select id="' + AddOns + '" class="form-control"></select></span><span id="AddOns"></span></td>' +
'</tr>';
("#tblFood").prepend(tr);
I'm trying to access the value of FoodCategory to disable the select of AddOns by
$('#'+FoodCategory).val() but it is not working.

HTML Element not being inserted

I'm working on a .NET Core project for my company where work orders are loaded from our SQL database using Entity Framework, filtered and then displayed as markers on a map through Google Maps API for our installers.
We have two types of filters: one that gets included in an Ajax POST, and one that filters locally to decrease load times and performance issues. What I'm trying to do is load the local filter items (lists that are included in the response when calling the initial Ajax POST). If the list of filter items exceeds 5 items, I want them to collapse to only 5 items and insert an anchor which expands (utilizes jQuery's toggle()) showing the rest of the items in that list.
This is the excerpt from the JavaScript function which takes care of that:
filterItems
.forEach((filterItem, i) => {
var localItem = '<label class="' + selectorContainerClass
+ ' selectorContainer" id="' + selectorContainerIdPrefix + filterItem.key
+ '"><input id="' + convertValToEng(filterItem.value)
+ '" type = "checkbox" class="filled-in navy" name="' + inputName
+ '" value="' + filterItem.key
+ '" onchange="localFilter(this, this.value)" /><span class="selector-value">'
+ filterItem.value
+ '</span> <span id="' + paramName + 'Cnt__' + filterItem.key
+ '" class="selector-count"></span></label ><br />';
document.querySelector("#" + colId).insertAdjacentHTML('beforeend', localItem);
if (i >= 5) {
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).addClass("collapse");
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).toggle(100);
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key + " + br").toggle(100);
}
});
if (filterItems.length > 5) {
//TODO: Fix the bug here; the .filter-collapse element is not being inserted under local installers.
var newEl = '<a class="filter-collapse" onclick="toggleFilterExpand(false, this)";><i class="material-icons">expand_more</i></a>';
document.getElementById(colId).insertAdjacentHTML('beforeend', newEl);
}
I should be getting a newEl inserted under the "Installer" column (8 installers, 3 of them not being displayed), but I'm not. I've tried jQuery's after() and insertAfter() methods, but neither of those worked. newEl is being generated for the "Area" column, as it should, but for the "Installer" column it's not.
I've also tried inserting the element manually through the console window with the exact same code and it works.
Would appreciate some help with this as I feel lost regarding this issue.
Thanks.
It turned out to be a stupid mistake on my end where I was removing the element newEl from the all the other filter lists before inserting a new one to the currently iterated one.

JQuery "Attribute Starts With" Selector Undefined

I have a modal dialog (Bootstrap) that has a list-group with custom list-group-items inside of it (populated by loop using append after adding data from my server).
Inside each list-group-item, I have a Checkbox that will be used to "select" the result. As I populate the items, I hook up the JQuery click event to the respective Checkbox:
// Add to search results
$('#search-results').append(
'<a id="centroid-list-item-' + featureAttrs['ObjectID'] + '" href="\\#"' + 'class="list-group-item" style="outline: 0">' +
'<table style="background: transparent">' +
'<tr>' +
'<td>' +
'<input id="centroid-checkbox-' + featureAttrs['ObjectID'] + '" type="checkbox" value=""> ' +
'</td>' +
'<td>' +
'<h4 class="list-group-item-heading">' +
featureAttrs['UNIQUEID'] +
'</h4>' +
'<p id="centroid-item-text-' + featureAttrs['ObjectID'] + '"' + 'class="list-group-item-text">' +
featureAttrs['NAME'] +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</a>'
);
// When the DOM is ready, add event
$(document).ready(function () {
$('#centroid-checkbox-' + featureAttrs['ObjectID']).click(function (event) {
var objectId = $(this).attr('id').replace(/^\D+/g, '');
console.log(objectId + " was clicked");
if ($(this).is(':checked')) {
// Enable the 'Set Target' button
$('#btn-set-target').removeAttr('disabled');
// Disable all other choices
$('[id^="centroid-checkbox-"]').each(function (event) {
console.log("Picked up values for checkboxes");
if ($(this).attr('id') != ('centroid-checkbox-' + objectId)) {
$(this).attr('disabled', true);
}
});
}
else {
$('#btn-set-target').attr('disabled', 'disabled');
// Enable all text boxes
$('[id^="centroid-checkbox-"]').each(function () {
if (this.attr('id') !== ('centroid-checkbox-' + objectId)) {
this.removeAttr('disabled');
}
});
}
});
});
The problem I am having is that when I call $('[id^="centroid-checkbox-"]') it is returning undefined. However, at the time is gets called, there are about 30 "centroid-checkbox-XXXXX" checkboxes. What am I doing wrong here?
The $ function never returns undefined.
But this in the callback you pass to each is an element, not a jQuery object.
Which means you must use this.id instead of this.attr('id') and $(this).removeAttr('disabled') instead of this.removeAttr('disabled') (and you probably want this.disabled=false or $(this).prop('disabled', false)).
objectId never gets defined because you need to quote enclose the regular expression you're using for replace():
var objectId = $(this).attr('id').replace(/^\D+/g, '');
should be:
var objectId = $(this).attr('id').replace('/^\D+/g', '');
DEMO: http://jsfiddle.net/4fUvn/8/

Getting Undefined when trying to get Value from Input box built thru jQuery

HTML:
<input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});'
<span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span>
Here is my JS code:
function RenameGlobalPhase(id)// {{{
{
var phase = $('#renameGlobalPhase' + id).html();
$('#renameGlobalPhase' + id).replaceWith("<input id='#renameGlobalPhase" + id + "' type='text' onblur='SaveNewPhaseName(" + id + ");' value='" + phase + "' />");
$('#renameGlobalPhase' + id).focus();
} // }}}
function SaveNewPhaseName(id)// {{{
{
var newPhase = $('#renameGlobalPhase' + id).val();
alert(newPhase);
$('#renameGlobalPhase' + id).replaceWith('<span>' + newPhase + '</span>');
} // }}}
So when user clicks the input button above, I turn a span next to it into an input field so user can rename the value. And in onblur (newly created from jQuery for that new input field), I want to save the new value and return back to span.
The alert shows an undefined value. Can anyone see what is wrong?
Remove the # from the id
Change
.replaceWith("<input id='#renameGlobalPhase" + id + "'
to
.replaceWith("<input id='renameGlobalPhase" + id + "'
fiddle

Workflow using Google Apps Script - I need to email the user in my first step

I'm creating a workflow process that will email a body of a form to users in that workflow. I can iterate through the users and send an email but I do not now how to pass the "e" parameters for the body of the email. I actually already have a function that will send the body , but I need to include this in my step process (I think).
Hear is my code that will send email
function sendEmail_(e) {
var sheet = SpreadsheetApp.openById("0AuCblud0Ss7sdfA1bXZjYXA0Y0IhthkhUQm5vWG02MVE").getActiveSheet();
var row = sheet.getLastRow()+1;
sheet.getRange(row,3).setValue(row);
var range = sheet.getRange(sheet.getLastRow(),1,1,23);
range.setValues([[e.parameter.LastName,e.parameter.FirstName,row /*e.parameter.DivisionName*/,e.parameter.EffectiveDate,e.parameter.Status,
e.parameter.Network,e.parameter.EmployeeNewPosition,e.parameter.DivisionFolder,e.parameter.SpecificIndividual,
e.parameter.Email,e.parameter.username,e.parameter.who,e.parameter.Banner,e.parameter.RMS ,e.parameter.HAPPY,e.parameter.Sweeps,
e.parameter.Comcate,e.parameter.Netviewer,e.parameter.NetDispatcher,e.parameter.IMARS,"pending", e.parameter.DivHeadEmail, e.parameter.Director]]);
var body = '<form action= <form action = " https://sites.google.com/a/macros/wichitafallstx.gov/s/AKfycbxAOGO6q9ofauf34xlDA9sLG8sUXeZsuvQkDKATOQ/exec" method ="post">' +
"<b>Last Name:</b>" + e.parameter.LastName + '<br><br>' +
"<b>First Name:</b>" + e.parameter.FirstName + '<br><br>' +
"<b>Division Name:</b>" + e.parameter.DivisionName + '<br><br>' +
"<b>Effective Date:</b>" + e.parameter.EffectiveDate + '<br><br>' +
"<b>Employee Status:</b>" + e.parameter.Status + '<br><br>' +
"<b>Network:</b>" + e.parameter.Network + '<br><br>' +
"<b>Employee New Position:</b>" + e.parameter.EmployeeNewPosition + '<br><br>' +
"<b>Division Folder:</b>" + e.parameter.DivisionFolder + '<br><br>' +
"<b>Specific Individual:</b>" + e.parameter.SpecificIndividual + '<br><br>' +
"<b>Email:</b>" + e.parameter.Email + '<br><br>' +
"<b>Username:</b>" + e.parameter.username + '<br><br>' +
"<b>who:</b>" + e.parameter.who + '<br><br>' +
"<b>Banner:</b>" + e.parameter.Banner + '<br><br>' +
"<b>RMS:</b>" + e.parameter.RMS + '<br><br>' +
"<b>HAPPY:</b>" + e.parameter.HAPPY + '<br><br>' +
"<b>Sweeps:</b>" + e.parameter.Sweeps + '<br><br>' +
"<b>Comcate:</b>" + e.parameter.Comcate + '<br><br>' +
"<b>Netviewer:</b>" + e.parameter.Netviewer + '<br><br>' +
"<b>NetDispatcher:</b>" + e.parameter.NetDispatcher + '<br><br>' +
"<b>IMARS:</b>" + e.parameter.IMARS +
'<br />' +
'<br />' +
'<input type="hidden" name="row" value=" ' + row +' "/>' +
'<input type="submit" value="Approve" onclick="approve()" />' +
'</form>'
;
// var owners = e.parameter.DivHeadEmail;
// var mail = MailApp.sendEmail(owners, "test",'' , {htmlBody:body});
}
I need to email the html body from the code above with the step in the work flow in this "createStep" function. I dont know how to reference the variable "body" from the code above to this function or even if I could include the html body in this function. How would I do this?
function createStep(approvers) {
var step = new Object();//javascript object
step['numberOfApprovers'] = approvers.length; //set number of approvers passed in array
step['approvers'] = approvers.slice(0); //slice copies array
step['status'] = 'pending'; //set statust to pedning
for (var i in approvers)
step[approvers[i]] = 'pending'; //iterate field that indicates specific status
for (var m in approvers)
step[approvers[m]] = MailApp.sendEmail(approvers, "test", "test",{htmlBody:body});
return step
}
If you want to include the body variable in both functions, declare the variable outside the functions:
var body;
function sendEmail_(e) {
...
body = ...
}
function createStep(approvers) {
...
sendEmail(..., {htmlBody:body}
..
}
However, I don't think you can send POST parameters to a script, GET should work. But I haven't tried it myself.
On second thought, and trying to understand the process, why not create a web app that just displays the info on the screen, with an Approve button under it, and send a link to that app to each approver?
Advantage is that you can give access to the script to logged in users only, and check that the right person is approving--makes it more safe.
Note that you can use the ObjDB library to easily retrieve a row from a spreadsheet:
http://www.harryonline.net/scripts/objdb-storing-data-with-google-apps-script/482
I would create a spreadsheet with two worksheets. The first contains the data, the second contains the list of approvers. One column in the first sheet indicates the last approver.
So your script checks the rows in the data worksheet, and sends an email containing the data of a row that has not been approved yet. It includes a link to approve. The receiver checks the data, and clicks on the link to approve.
This brings him to a script, where he has to log in. The script checks the user with the expected approver, and if OK, increases the value in the approver column in the data sheet. While there are more approvers, continue the loop.

Categories

Resources