I have an XML file containing the same element name more than once, like below. I can only retrieve the first one. Would like to know how to retrieve all 4 "comments" using JavaScript. Thanks!
<FRIENDSSTATUS>
<STATUSFRIENDS id="2">
<STATUS>Life begins at the end of your comfort zone</STATUS>
<DATETIME>2012-10-30 10:32:28</DATETIME>
<FIRSTNAME>Malcolm</FIRSTNAME>
<LASTNAME>Landgraab</LASTNAME>
<COMMENTS datetime="2012-11-18 22:13:28" firstname="Ian" lastname="Tellerman">rr</COMMENTS>
<COMMENTS datetime="2012-11-18 22:13:39" firstname="Ian" lastname="Tellerman">hello</COMMENTS>
<COMMENTS datetime="2012-11-19 14:36:24" firstname="Ian" lastname="Tellerman">test</COMMENTS>
<COMMENTS datetime="2012-11-19 14:45:52" firstname="Ian" lastname="Tellerman">test4</COMMENTS>
</STATUSFRIENDS>
<STATUSFRIENDS id="3">
<STATUS>Prometheus. Fantastic film!!!!</STATUS>
<DATETIME>2012-10-30 10:32:28</DATETIME>
<FIRSTNAME>Mansa</FIRSTNAME>
<LASTNAME>Bendett</LASTNAME>
<COMMENTS datetime="2012-11-18 22:14:46" firstname="Ian" lastname="Tellerman">wrong</COMMENTS>
</STATUSFRIENDS>
</FRIENDSSTATUS>
The javascript codes:
xmlDoc = xmlhttp.responseXML;
$table = "<table border='1'>";
var element = xmlDoc.getElementsByTagName("FRIENDSSTATUS");
var elements = xmlDoc.getElementsByTagName("STATUSFRIENDS");
var comments = xmlDoc.getElementsByTagName("COMMENTS");
if(xmlDoc.documentElement !== null)
{
var root;
if (navigator.userAgent.indexOf("Firefox") > 0 )
var root = element[0].childElementCount;
if (navigator.userAgent.indexOf("MSIE") > 0 )
var root = xmlDoc.documentElement.childNodes.length;
for(i=0; i<root; i++){
$strStats = "";
$strComments = "";
$strDateTime = "";
$strFirstname = "";
$strLastname = "";
$strCommentDateTime = "";
$strCommentFirstName = "";
$strCommentLastName = "";
$strStatusID = "";
if(navigator.userAgent.indexOf("Firefox") > 0 ){
for(y=0;y < elements[i].childElementCount;y++)
{
$strStatusID = elements[i].getAttribute("id");
if(strStatus = elements[i].getElementsByTagName("STATUS"))
{
$strStats = strStatus[0].firstChild.nodeValue;
}
if(strStatus = elements[i].getElementsByTagName("DATETIME"))
{
$strDateTime = strStatus[0].firstChild.nodeValue;
}
if(strStatus = elements[i].getElementsByTagName("FIRSTNAME"))
{
$strFirstname = strStatus[0].firstChild.nodeValue;
}
if(strStatus = elements[i].getElementsByTagName("LASTNAME"))
{
$strLastname = strStatus[0].firstChild.nodeValue;
}
if(strComm = elements[i].getElementsByTagName("COMMENTS"))
{
$strComments = strComm[0].firstChild.nodeValue;
$strCommentDateTime = comments[i].getAttribute("datetime");
$strCommentFirstName = comments[i].getAttribute("firstname");
$strCommentLastName = comments[i].getAttribute("lastname");
$strComments += "<br>" + $strCommentFirstName + " " + $strCommentLastName + " " + $strCommentDateTime + "</br></br>";
}
$strStats = $strStats + " " + $strLastname + " " + $strFirstname + " " + $strDateTime;
$strFullName = $strFirstname + " " + $strLastname;
$strDateTime = "";
$strFirstname = "";
$strLastname = "";
}
}
Assign your XML to a variable, (myXmlString in this example), and read it as follows:
var parser=new DOMParser();
doc=parser.parseFromString(myXmlString,'text/xml');
var comments = doc.getElementsByTagName("COMMENTS") // Returns a array of those "comments".
An example of how to access the comments of the first STATUSFRIENDS. jsFiddle demo here.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
var xml = parseXml(xmlStr); // assuming xmlStr contains your XML
var commentsList = xml.documentElement.childNodes[0].getElementsByTagName("COMMENTS");
var output = "";
for(var i=0; i<commentsList.length; i++)
{
output += commentsList[i].firstChild.nodeValue + "<br />";
}
document.getElementById("comments").innerHTML = output;
Something like this:
var str = 'your XML as a string',
parser, xml;
if (window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(str, "text/xml");
}
else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(str);
}
var nodes = xml.childNodes[0].getElementsByTagName('COMMENTS');
var i, l = nodes.length, comments = [];
for (i = 0; i < l; i++) {
comments.push({
firstname: nodes[i].getAttribute('firstname'),
lastname: nodes[i].getAttribute('lastname'),
datetime: nodes[i].getAttribute('datetime'),
content: nodes[i].childNodes[0].nodeValue
});
}
console.log(comments);
I don't have time to post a full code sample, but JS supports XPath and you can get the Comments with this Qpath query:
/FRIENDSSTATUS/STATUSFRIENDS[#id="3"]/COMMENTS
Here is where I tested the Xpath syntax: http://chris.photobooks.com/xml/default.htm
Related
I have a situation here. My company has a webpage which we use for ticket creation. The user gets the email and he has to create a ticket based on the info in the email. I tried to automate this process however got stuck at uploading the attachment.
When the user click on the attach button, a new pop up opens and my macro looses the control over the pop up.
So currently what am doing is,
Save the email - which needs to be attached.
Copy the path to clip board using a function
run a vb script to paste and enter using send keys with 5 seconds delay
click on the attach button.
So before the macro clicks the attach button, a VBS runs behind to paste and hit enter. So by the time the pop up opens VBS starts and closes the pop up.
I was checking to run the attach function within VB script so that I dont have to click on attach button. But I am not able to reach anywhere. anyone help?
The below are the functions available in the webpage. I dont know which one to run and how.
<script eval="true">/**
* Validate the attachments to see if at least
* one file is attached. Otherwise, show an alert.
*
* #returns {Boolean}
*/
function validateAttachment() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (fileFields[i] && fileFields[i].value != "") {
setAttachButton(""); //disable
$('please_wait').style.display = "";
return true;
}
}
alert("Choose a file to attach");
return false;
}
/**
* Does the first attachment input field have a value?
* If not, use the grey button and change type of cursor.
* #param value
*/
function setDeleteButton(value) {
var field = $$('.attachmentRow')[0];
var text = field.select('input')[0];
var deleteButton = field.select('a.attachfile-delete img')[0];
if (!text.getValue().empty()) {
deleteButton.setAttribute('src', 'images/icons/kb_no.gif');
deleteButton.up().style.cursor = 'pointer';
} else {
deleteButton.setAttribute('src', 'images/icons/kb_no_disabled.gif');
deleteButton.up().style.cursor = 'default';
}
}
/**
* If the value passed in is an empty string,
* set the button to disabled state, otherwise
* enabled.
*
* #param value
*/
function setAttachButton(value) {
var attachButton = $("attachButton");
if (value == "")
attachButton.disabled = "true";
else
attachButton.disabled = "";
}
/**
* This controls the remove button for all attachments.
* If there are attachments in the list enable the button.
* Else keep disabled.
*
* #param e
*/
function setRemoveButton(e) {
var removeButton = gel("removeButton");
var deletedSysIdsElement = gel("deleted_sys_ids");
var deletedSysIds = new Array();
var deletedString = deletedSysIdsElement.value;
if (deletedString)
deletedSysIds = deletedString.split(";");
var thisId = e.name.substring(7);
if (e.checked) {
removeButton.disabled = "";
deletedSysIds.push(thisId);
} else {
var index = deletedSysIds.indexOf(thisId);
deletedSysIds.splice(index, 1);
// are there any left checked?
var inputs = document.getElementsByTagName("input");
var nonechecked = true;
var i = 0;
while(i < inputs.length && nonechecked) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
if (inputs[i].checked)
nonechecked = false;
i++;
}
if (nonechecked) {
removeButton.disabled = "true";
}
}
deletedSysIds = deletedSysIds.join(";");
deletedSysIdsElement.value = deletedSysIds;
}
function startRemoveAttachments() {
var removeButton = gel("removeButton");
removeButton.disabled = true;
gel('please_wait').style.display = "";
var thisUrl = gel("sysparm_this_url");
thisUrl.value = "attachment_deleted.do?sysparm_domain_restore=false&sysparm_nostack=yes&sysparm_deleted=" + gel("deleted_sys_ids").value;
return true;
}
/**
* Clear and Remove the attachment field that is
* passed in.
*
* #param field_id
*/
function clearAttachmentField(field) {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
fileFields[0].setAttribute('data-position', 'first');
if (fileFields.size() > 1 && (field.readAttribute('data-position') != "first")) {
//check if field you are removing has a 3rd column (does it have an attach button?)
var needToAttachButton;
var attachButton = field.select('td')[2];
if (attachButton)
needToAttachButton = true;
//remove the field
field.remove();
//if you removed a field with a third column, add an attachbutton onto the new "first" field.
if (attachButton) {
var attachButton = new Element('input', {
"type": "submit",
"id": "attachButton",
"disabled": "true",
"value": "Attach" });
var td = new Element('td', {align: 'right'}).update(attachButton);
Element.extend(td);
form.select('.attachmentRow').first().select('td')[1].insert({'after': td});
}
}
else
clearFileField(field.select('td').first().select('input').first());
checkAndSetAttachButton();
}
/**
* Check all attachment input fields. If there is not attachment
* currently, disable the attachment button, else enable it.
*
* #returns
*/
function checkAndSetAttachButton() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
var validFileCount = 0;
for (var i = 0; i < fileFields.size(); i++) {
var field = fileFields[i].select('td').first().select('input').first();
if (field.getValue() != "") {
if (window.File && window.FileReader && window.FileList)
validFileCount += validateSizeandExt(field);
else
validFileCount += 1;
}
}
if (validFileCount == 0)
setAttachButton("");
else
setAttachButton("true");
}
function validateSizeandExt(field) {
var form = $('sys_attachment');
var maxSize = (form.max_size && form.max_size.value) ? form.max_size.value : 0;
var fileTypes = (form.file_types && form.file_types.value) ? form.file_types.value : "";
var files = field.files;
var allowedSize = maxSize * 1048576;
var warningString = "";
var checkJEXL = true;
for (var i = 0; i < files.length; i++) {
if (checkJEXL && isJEXLExpression(files[i].name)) {
warningString += files[i].name + " is an invalid file name.\n";
}
if (files[i].size > allowedSize && allowedSize != 0)
warningString += files[i].name + " is " + getDisplaySize(files[i].size) + ". The maximum file size is " + getDisplaySize(allowedSize) + ".\n";
if (!isValidFileType(files[i], fileTypes))
warningString += files[i].name + " has a prohibited file extension." + "\n";
}
if (warningString != "") {
alert(warningString);
clearFileField(field);
return 0;
}
return 1;
}
function isJEXLExpression(fileName) {
var phaseOneOpening = fileName.indexOf("$" + "{");
var phaseTwoOpening = fileName.indexOf("$" + "[");
if (phaseOneOpening != -1 || phaseTwoOpening != -1) {
return true;
}
return false;
}
function getDisplaySize(sizeInBytes) {
var kilobytes = Math.round(sizeInBytes / 1024);
if (kilobytes < 1)
kilobytes = 1;
var reportSize = kilobytes + "K";
if (kilobytes > 1024)
reportSize = Math.round(kilobytes / 1024) + "MB";
return reportSize;
}
function isValidFileType(file, types) {
var extensions = types || "";
if (extensions != "") {
extensions.toLowerCase();
extensions = extensions.split(",");
var periodIndex = file.name.lastIndexOf(".");
var extension = file.name.substring(periodIndex+1).toLowerCase();
if (extensions.indexOf(extension) == -1)
return false;
}
return true;
}
/**
* Clear a given field's contents.
*
* #param field
* the field element.
*/
function clearFileField(field) {
$(field).clear();
$(field).parentNode.innerHTML = $(field).parentNode.innerHTML;
checkAndSetAttachButton();
}
/**
* If the attachments are uploaded, clear any extra attachment input fields so
* they do not take up as much screen space. Additionally, clear the first field
* and keep it showing.
*/
function clearAttachmentFields() {
var form = $('sys_attachment');
var fileFields = form.select('.attachmentRow');
for (var i = 0; i < fileFields.size(); i++) {
if (i == 0)
clearFileField(fileFields[0].select('td').first().select('input').first());
if (i > 0)
fileFields[i].remove();
}
checkAndSetAttachButton();
setDeleteButton();
}
// this get called after an attachment is uploaded to update the display
function refreshAttachments(id, fileName, canDelete, createdBy, createdOn, contentType, encryption, iconPath) {
refreshLiveFeedAttachments(id, fileName, contentType, iconPath);
var encryptCheck = gel("encrypt_checkbox");
if (encryptCheck) {
encryptCheck.checked = false;
$('sysparm_encryption_context').value = "";
}
gel("please_wait").style.display = "none";
// if we didn't get an id, we could not read the attachment due to business rules so we're done
if (typeof id == "undefined")
return;
var noAttachments = gel("no_attachments");
if (noAttachments.style.display == "block")
noAttachments.style.display = "none";
// add the new upload to the display
var table = gel("attachment_table_body");
var tr = cel("tr");
var td = cel("td");
td.style.whiteSpace = "nowrap";
td.colspan = "2";
if (canDelete=="true") {
var input = cel("input");
var checkId = "sys_id_" + id;
input.name = checkId;
input.id = checkId;
input.type = "checkbox";
input.onclick = function() {setRemoveButton(gel(checkId));};
td.appendChild(input);
gel("delete_button_span").style.display = "inline";
var text = document.createTextNode(" ");
td.appendChild(text);
input = cel("input");
input.type = "hidden";
input.name = "Name";
input.value = "false";
td.appendChild(input);
}
var attachment_input = cel("input");
attachment_input.className = "attachment_sys_id";
attachment_input.type = "hidden";
attachment_input.id = id;
td.appendChild(attachment_input);
var anchor = cel("a");
anchor.style.marginRight = "4px";
anchor.href = "sys_attachment.do?sys_id=" + id;
anchor.title = "Attached by " + createdBy + " on " + createdOn;
var imgSrc = iconPath;
if (encryption != "") {
anchor.title += ", Encrypted: " + encryption;
imgSrc = "images/icons/attachment_encrypted.gifx";
}
var img = cel("img");
img.src = imgSrc;
img.alt = anchor.title;
anchor.appendChild(img);
var text = $(cel('a'));
getMessage("Download {0}", function(msg) {
text.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
text.href = "sys_attachment.do?sys_id=" + id;
text.onkeydown = function(event){return allowInPlaceEditModification(text, event);};
text.style.marginRight = "5px";
text.style.maxWidth = "75%";
text.style.display = "inline-block";
text.style.overflow = "hidden";
text.style.verticalAlign = "middle";
if ('innerText' in text)
text.innerText = fileName;
else
text.textContent = fileName;
text.setAttribute("data-id", id);
text.inPlaceEdit({
selectOnStart: true,
turnClickEditingOff: true,
onBeforeEdit: function() {
text.lastAriaLabel = text.getAttribute("aria-label");
text.removeAttribute("aria-label");
text.setAttribute("role", "textbox");
},
onEditCancelled: function() {
text.removeAttribute("role");
if (text.lastAriaLabel) {
text.setAttribute("aria-label", text.lastAriaLabel);
}
},
onAfterEdit: function(newName) {
var oldName = this.oldValue;
var ga = new GlideAjax('AttachmentAjax');
ga.addParam('sysparm_type', 'rename');
ga.addParam('sysparm_value', id);
ga.addParam('sysparm_name', newName);
ga.getXML(function(response){
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer !== '0')
alert(new GwtMessage().getMessage("Renaming attachment {0} to new name {1} is not allowed", oldName, newName));
$$('a[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
$$('span[data-id="' + id + '"]').each(function(elem){
if ('innerText' in elem)
elem.innerText = (answer === '0') ? newName : oldName;
else
elem.textContent = (answer === '0') ? newName : oldName;
});
/*
This routine updates the attachment in the attachment modal AND the same attachment on the parent form
*/
getMessage(["Download {0}", "View {0}", "Rename {0}"], function(msg) {
var newDownloadText = new GwtMessage().format(msg["Download {0}"], newName);
var newViewText = new GwtMessage().format(msg["View {0}"], newName);
var newRenameText = new GwtMessage().format(msg["Rename {0}"], newName);
console.log(id)
$$('a[data-id="' + id + '"]').each(function(elem){
elem.setAttribute("aria-label", newDownloadText);
})
$$('.view_' + id).each(function(elem){
elem.setAttribute("aria-label", newViewText);
})
$$('.rename_' + id).each(function(elem){
elem.setAttribute("aria-label", newRenameText);
})
})
text.removeAttribute("role");
});
}
});
if (contentType == "text/html")
anchor.target = "_blank";
td.appendChild(anchor);
td.appendChild(text);
var allowRename = gel('ni.show_rename_link').value;
if (allowRename == "true") {
var renameAttachment = $(cel('a'));
renameAttachment.href = "#";
renameAttachment.setAttribute("role", "button");
getMessage("Rename {0}", function(msg) {
renameAttachment.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
renameAttachment.className = 'attachment rename_' + id;
renameAttachment.onclick = function() {
text.beginEdit();
};
renameAttachment.innerHTML = '[rename]';
td.appendChild(renameAttachment);
}
var showView = gel("ni.show_attachment_view").value;
if (showView == "true") {
var blank = document.createTextNode(" ");
tr.appendChild(blank);
var view = cel("a");
view.href = "#";
getMessage("View {0}", function(msg) {
view.setAttribute("aria-label", new GwtMessage().format(msg, fileName));
});
var newText = document.createTextNode('[view]');
view.appendChild(newText);
view.className = "attachment view_" + id;
if (showPopup == "false")
view.href = "sys_attachment.do?sys_id=" + id + "&view=true";
else
view.onclick = function() {
tearOffAttachment(id)
};
td.appendChild(blank);
td.appendChild(view);
}
var showPopup = gel("ni.show_attachment_popup").value;
tr.appendChild(td);
table.appendChild(tr);
//If a new attachment is added check if attachments are marked for edge encryption before showing the Download all button
if (!edgeEncryptionEnabledForAttachments && hasAttachments()){
gel("download_all_button").style.display = "inline";
}
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.uploaded', {
sysid: id,
name: fileName,
hoverText: anchor.title,
image: imgSrc,
showRename: allowRename,
showView: showView,
showPopup: showPopup
});
}else{
addAttachmentNameToForm(id, fileName, anchor.title, imgSrc, allowRename, showView, showPopup);
}
if (g_accessibility)
alert(fileName + " " + anchor.title);
}
function refreshLiveFeedAttachments(sys_id, fileName, contentType, iconPath) {
var p = gel('live_feed_message_images');
if (!p)
return;
if (!contentType)
return;
if (contentType.indexOf('image') != 0 || contentType.indexOf('image/tif') == 0)
refreshLiveFeedNonImages(p, sys_id, iconPath, fileName);
else
refreshLiveFeedImages(p, sys_id, fileName);
var container = $('live_feed_image_container');
if (container)
container.show();
}
function refreshLiveFeedNonImages(p, sys_id, iconPath, fileName) {
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = iconPath;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
var span = cel('span');
span.setAttribute('data-id', sys_id);
if ('innerText' in span)
span.innerText = fileName;
else
span.textContet = fileName;
a.appendChild(span);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
function refreshLiveFeedImages(p, sys_id, fileName) {
var imageName = "sys_attachment.do?sys_id=" + sys_id;
var a = cel('a');
a.onclick = function() {tearOffAttachment(sys_id)};
a.title = fileName;
a.className = "live_feed_attachment_link";
var img = cel('img');
img.src = imageName;
img.className = 'live_feed_image_thumbnail';
img.setAttribute("data-sys_id", sys_id);
a.appendChild(img);
p.appendChild(a);
p.appendChild(cel('br'));
setTimeout(this.hideLoading.bind(this), 200);
}
// this get called after attachments are deleted to update the display
function deletedAttachments(sysIds) {
var form_table_id = "";
if(gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")){
form_table_id = (gel("sys_uniqueValue") || gel("sysparm_attachment_cart_id")).value;
}
if(form_table_id && attachmentParentSysId != form_table_id){
CustomEvent.fire('record.attachment.deleted', sysIds);
return;
}
deleteLiveFeedAttachments(sysIds);
var modified = $("attachments_modified");
if (modified)
modified.value = "true";
var header_attachment = $('header_attachment');
gel("deleted_sys_ids").value = ""; // there should be none on the list once we return
var idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var id = idArray[i];
changeCount(attachmentParentSysId, 'decrease');
var e = gel("sys_id_" + id);
var tr = e.parentNode.parentNode;
rel(tr);
e = gel("attachment_" + id);
if (e)
rel(e);
}
var inputs = document.getElementsByTagName("input");
var anAttachment = false;
var i = 0;
while(i < inputs.length && !anAttachment) {
if (inputs[i].type == "checkbox" && inputs[i].name.substring(0, 7) == "sys_id_")
anAttachment = true;
i++;
}
if (!anAttachment) {
var noAttachments = gel("no_attachments");
noAttachments.style.display = "none";
var removeButton = gel("removeButton");
removeButton.disabled = true;
var downloadAllButton = gel("download_all_button");
downloadAllButton.style.display = "none";
gel('delete_button_span').style.display = "none";
hideObject($("header_attachment_list_label"));
if (header_attachment)
header_attachment.style.height = "auto";
var line = $("header_attachment_line");
if (line) {
line.style.visibility = "hidden";
line.style.display = "none";
}
}
gel("please_wait").style.display = "none";
var more_attachments = $('more_attachments');
if (more_attachments && header_attachment)
if( (computeAttachmentWidth() - 20) >= (header_attachment.getWidth() - more_attachments.getWidth()))
more_attachments.style.display = 'block';
else
more_attachments.style.display = 'none';
}
function deleteLiveFeedAttachments(sysIds) {
var p = $('live_feed_message_images');
if (!p)
return;
if (!p.visible())
return;
idArray = sysIds.split(";");
for (var i=0; i<idArray.length; i++) {
var imgs = p.select("img.live_feed_image_thumbnail");
if (imgs.length < 1)
return;
for (var j=0; j<imgs.length; j++) {
if (imgs[j].getAttribute("data-sys_id") == idArray[i]) {
var elem = imgs[j].up("a.live_feed_attachment_link");
elem.remove();
if (elem.next() && (elem.next().tagName.toLowerCase() == "br"))
elem.next().remove();
}
}
}
if (p.select("img.live_feed_image_thumbnail").length > 0)
return;
var container = $('live_feed_image_container');
if (container)
container.hide();
}
function computeAttachmentWidth() {
var temp = $('header_attachment_list').select('li');
var totalWidth = 0;
for (var i = 0; i < temp.length; i++) {
totalWidth += temp[i].getWidth();
}
return totalWidth;
}
function closeAttachmentWindow() {
GlideModal.prototype.get('attachment').destroy();
}
/**
* Add an input field to the file browser in the dialog.
* This is called when the "Add Another Attachment" button
* is clicked.
* */
function addRowToTable() {
var formRows = $('sys_attachment').select(".attachmentRow");
var input = "<input type='file' title='Attach' " +
"name='attachFile' onchange='checkAndSetAttachButton(); setDeleteButton(this.value);'" +
"size=41 multiple=true />";
var img = "<a href='#' onclick='clearAttachmentField($(this).up().up()); setDeleteButton(this.value);'>" +
"<img src='images/icons/kb_no.gif'/></a>";
var row = "<tr class='attachmentRow'><td> "
+ input + "</td><td align='right'>" + img + "</td></tr>";
formRows.last().insert({ "after" : row });
}
/**
* Download all attachments
*/
function downloadAllAttachments(){
var downloadUrl = window.location.protocol + '//' + window.location.host + '/download_all_attachments.do?sysparm_sys_id=' + attachmentParentSysId;
window.location = downloadUrl;
}
function hasAttachments(){
return document.getElementsByClassName("attachment_sys_id").length > 0;
}</script>
This is what happens when I click on the attach button in the HTML. attachFile is the ID which I am using in my code to run.
<tr class="attachmentRow">
<td id="attachFileCell" colspan="3">
<input name="attachFile" title="" id="attachFile" onchange="checkAndSetAttachButton(); setDeleteButton(this.value); $('attachButton').click();" type="file" size="41" multiple="true" data-original-title="Attach">
<a class="attachfile-delete" style="display: none; cursor: default;" onclick="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);" href="#">
<img src="images/icons/kb_no_disabled.gif">
</a>
<input disabled="" class="attachfile-attach button" id="attachButton" style="display: none;" type="submit" value="Attach">
</td>
</tr>
This is my VBA Code which I used.
Set IE = New SHDocVw.InternetExplorer
IE.Visible = True
IE.Navigate "https://sorry cant share the link as per the company policy"
Do While IE.Busy = True Or IE.READYSTATE <> 4: DoEvents: Loop
Set HTMLDoc = IE.Document
'***************** Save Email
eachitem.SaveAs StrFile, 3
'***************** file link to clipboard
CopyText StrFile
'***************** Attach Email
HTMLDoc.getElementById("header_add_attachment").Click
Application.Wait (Now() + TimeValue("00:00:02"))
'***************** Call external VBS file to handle the pop up then attach
Shell "Explorer.exe " & StrFolderPath & "SNOW.vbs", vbNormalFocus
HTMLDoc.getElementById("attachFile").Click
SendKeys "{Enter}", True
I tried the below method to call the function, but reaching nowhere! Any assistance would be appreciated. I really dont know which function attaches the file to the website and how.
Set HTMLDoc1 = IE.Document.parentWindow
HTMLDoc1.execScript code:="isJEXLExpression(" & StrFile & ")"
HTMLDoc1.execScript code:="checkAndSetAttachButton()"
HTMLDoc1.execScript code:="setDeleteButton(this.value)"
HTMLDoc1.execScript code:="$('attachButton').click()"
HTMLDoc1.execScript code:="clearAttachmentField($(this).up().up()); setDeleteButton(this.value);"
so im trying to extract data from a xml file which looks like this:
<example>
<phrase>phrase1</phrase>
<word>
<definition>definition1</definition>
</word>
<word>
<definition>definition2</definition>
</word>
</example>
I want to be able to put definition1 and definition2 as seperate members of an array, for now i get them merged like this: definition1definition2
this is my code:
var $example = $xml.find("example");
$example.each(function(){
list.push($(this).children("word").children("definition").text());
});
Does anyone have an idea?
thanks
If you want to use JQuery, you need to change the
$example.each(function(){
list.push($(this).children("word").children("definition").text());
});
to
$example.children("word").children("definition").each(
function() {
list.push($(this).text());
});
Check out this Fiddle.
$(document).ready(function() {
var xml =
'<example>' +
'<phrase>phrase1</phrase>' +
'<word>' +
'<definition>definition1</definition>' +
'</word>' +
'<word>' +
'<definition>definition2</definition>' +
'</word>' +
'</example>' +
'';
var xmlDoc = new DOMParser().parseFromString(xml, 'text/xml');
var x = xmlDoc.documentElement.childNodes;
var list = [];
for (i = 0; i < x.length; i++) {
if (x[i].nodeName == 'word') {
console.log(x[i].childNodes[0].innerHTML);
list.push(x[i].childNodes[0].innerHTML);
}
}
document.getElementById('demo').innerHTML = list;
console.log(list);
});
jquery solution
$example.find("word > definition").map(function(){ return $(this).text()}).toArray()
var xml =
'<example>' +
'<phrase>phrase1</phrase>' +
'<word>' +
'<definition>definition1</definition>' +
'</word>' +
'<word>' +
'<definition>definition2</definition>' +
'</word>' +
'</example>' +
'';
var xmlDoc = new DOMParser().parseFromString(xml, 'text/xml');
var list = $("example > word > definition",xmlDoc).map(function(){ return $(this).text()}).toArray();
console.log(list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
vanila js solution
// Code goes here
var list = [];
var txt = `<example>
<phrase>phrase1</phrase>
<word>
<definition>definition1</definition>
</word>
<word>
<definition>definition2</definition>
</word>
</example>`;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var elements = xmlDoc.getElementsByTagName("definition");
[].forEach.call(elements, function(el) {
list.push(el.textContent)
});
console.log(list);
I'm integrating a widget into my page (Houzz). It works, but only if I remove all xlinks in my SVGs. If there are any xlinks, I get the error:
TypeError: elem.className.split is not a function
The SVG is:
<svg version="1.1" id="Layer_4_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="1309.016px" height="634.008px" viewBox="0 0 1309.016 634.008" enable-background="new 0 0 1309.016 634.008"
xml:space="preserve" class="js-animate" style="max-width: 100%;">
<a xlink:type="simple" xlink:href="/meet-the-team"></a>
</svg>
The script is:
(function(d,s,id){if(!d.getElementById(id)){var js=d.createElement(s);js.id=id;js.async=true;js.src="//platform.houzz.com/js/widgets.js?"+(new Date().getTime());var ss=d.getElementsByTagName('script')[0];ss.parentNode.insertBefore(js,ss);}})(document,"script","houzzwidget-js");
I've created a fiddle, but that's displaying different behaviour - I have to remove the width / height from the svg to make the widget work:
https://jsfiddle.net/v0fkr8jx/
My test page:
http://uprightconstruction.co.uk/index2
Here's the Houzz script being referenced. The error is around line 16 going by Firebug:
window.hzmr = window.hzmr || []; window.hzmr.push("widgets:2406");
(function() {
function createIFrame(width, height) {
var iframeElem = document.createElement('iframe');
iframeElem.setAttribute("scrolling","no");
iframeElem.allowTransparency = true;
iframeElem.border = 0;
iframeElem.frameBorder = 0;
iframeElem.style.border = 'none';
iframeElem.width = width;
iframeElem.height = height;
return iframeElem;
}
function containsClassName(elem, className) {
var classNames = elem.className.split(' ');
for(var i=0; i<classNames.length; i++) {
if(className == classNames[i]) {
return true;
}
}
return false;
}
function cleanLocale(locale) {
var knownLocales = {"en-us":true,"en-gb":true,"en-au":true,"de-de":true,"fr-fr":true,"ru-ru":true,"ja-jp":true,"it-it":true,"es-es":true,"da-dk":true,"nb-no":true,"fi-fi":true,"sv-se":true,"en-ie":true,"en-nz":true,"en-sg":true,"en-in":true};
if(locale && locale.toLowerCase() in knownLocales) {
return locale.toLowerCase();
}
return 'en-us';
}
function processWidgets(domId) {
var links = [];
if(typeof domId == 'string') {
if(domId.charAt(0) == '#') {
domId = domId.substr(1);
}
var elem = document.getElementById(domId);
if(elem) {
links.push(elem);
}
} else if(typeof domId != 'undefined' && ('nodeName' in domId)) {
links.push(domId);
} else {
links = document.getElementsByTagName('a');
}
var pid = new Date().getTime() + '' + Math.floor(Math.random()*1000000);
var houzzLinks = [];
var houzzReviews = [];
for (var i=0; i < links.length; i++) {
if(containsClassName(links[i],'houzz-share-button')) {
houzzLinks.push(links[i]);
} else if(containsClassName(links[i], 'houzz-review-widget')) {
houzzReviews.push(links[i]);
}
}
for (var i=0; i < houzzReviews.length; i++) {
var review = houzzReviews[i];
var pro = review.getAttribute('data-pro');
var mini = review.getAttribute('data-size');
mini = (mini == 'mini');
var locale = cleanLocale(review.getAttribute('data-locale'));
var iframeWidth = mini?225:300;
var iframeHeight = mini?130:435;
if(pro) {
var reviewUrls = {"en-us":"http:\/\/www.houzz.com\/reviewWidget","en-gb":"http:\/\/www.houzz.co.uk\/reviewWidget","en-au":"http:\/\/www.houzz.com.au\/reviewWidget","de-de":"http:\/\/www.houzz.de\/reviewWidget","fr-fr":"http:\/\/www.houzz.fr\/reviewWidget","ru-ru":"http:\/\/www.houzz.ru\/reviewWidget","ja-jp":"http:\/\/www.houzz.jp\/reviewWidget","it-it":"http:\/\/www.houzz.it\/reviewWidget","es-es":"http:\/\/www.houzz.es\/reviewWidget","da-dk":"http:\/\/www.houzz.dk\/reviewWidget","nb-no":"http:\/\/www.houzz.no\/reviewWidget","fi-fi":"http:\/\/www.houzz.fi\/reviewWidget","sv-se":"http:\/\/www.houzz.se\/reviewWidget","en-ie":"http:\/\/www.houzz.ie\/reviewWidget","en-nz":"http:\/\/www.houzz.co.nz\/reviewWidget","en-sg":"http:\/\/www.houzz.com.sg\/reviewWidget","en-in":"http:\/\/www.houzz.in\/reviewWidget"};
var iframeSrc = reviewUrls[locale] + '/' + encodeURIComponent(pro) + '/' + (mini?'mini':'');
var iframeElem = createIFrame(iframeWidth, iframeHeight);
review.parentNode.replaceChild(iframeElem, review);
iframeElem.src = iframeSrc;
}
}
for (var i=0; i < houzzLinks.length; i++) {
var link = houzzLinks[i];
var imageURL = link.getAttribute('data-img');
var linkURL = link.getAttribute('data-url');
var title = link.getAttribute('data-title');
var showCount = link.getAttribute('data-showcount') == '1';
var hzID = link.getAttribute('data-hzid');
var whiteBg = link.getAttribute('data-whitebg');
var format = link.getAttribute('data-format');
var locale = cleanLocale(link.getAttribute('data-locale'));
var identifier = i + '' + Math.floor(Math.random()*1000000);
link.id = 'hzbtn' + identifier;
var referer = document.location.href;
var buttonWidths = {"en-us":52,"en-gb":52,"en-au":52,"de-de":75,"fr-fr":88,"ru-ru":52,"ja-jp":52,"it-it":52,"es-es":52,"da-dk":52,"nb-no":52,"fi-fi":52,"sv-se":52,"en-ie":52,"en-nz":52,"en-sg":52,"en-in":52};
var buttonWidth = buttonWidths[locale];
var buttonUrls = {"en-us":"http:\/\/www.houzz.com\/buttonWidget","en-gb":"http:\/\/www.houzz.co.uk\/buttonWidget","en-au":"http:\/\/www.houzz.com.au\/buttonWidget","de-de":"http:\/\/www.houzz.de\/buttonWidget","fr-fr":"http:\/\/www.houzz.fr\/buttonWidget","ru-ru":"http:\/\/www.houzz.ru\/buttonWidget","ja-jp":"http:\/\/www.houzz.jp\/buttonWidget","it-it":"http:\/\/www.houzz.it\/buttonWidget","es-es":"http:\/\/www.houzz.es\/buttonWidget","da-dk":"http:\/\/www.houzz.dk\/buttonWidget","nb-no":"http:\/\/www.houzz.no\/buttonWidget","fi-fi":"http:\/\/www.houzz.fi\/buttonWidget","sv-se":"http:\/\/www.houzz.se\/buttonWidget","en-ie":"http:\/\/www.houzz.ie\/buttonWidget","en-nz":"http:\/\/www.houzz.co.nz\/buttonWidget","en-sg":"http:\/\/www.houzz.com.sg\/buttonWidget","en-in":"http:\/\/www.houzz.in\/buttonWidget"};
var iframeSrc = buttonUrls[locale] + '?url='
+ encodeURIComponent(linkURL);
if(imageURL) {
iframeSrc += '&img=' + encodeURIComponent(imageURL);
}
if(title) {
iframeSrc += '&title=' + encodeURIComponent(title);
}
if(showCount) {
iframeSrc += '&count=1';
}
if(whiteBg) {
var whiteBgValue = 0;
if(String(whiteBg) == '1' || whiteBg.toLowerCase() == 'true') {
whiteBgValue = 2;
} else if(String(whiteBg) == '0' || whiteBg.toLowerCase() == 'false') {
whiteBgValue = 1;
}
iframeSrc += '&whiteBg=' + encodeURIComponent(whiteBgValue);
}
if(hzID) {
iframeSrc += '&hzid=' + encodeURIComponent(hzID);
}
iframeSrc += '&locale=' + encodeURIComponent(locale);
iframeSrc += '&ref=' + encodeURIComponent(referer);
iframeSrc += '&pid=' + encodeURIComponent(pid);
if(format == 'custom') {
if(link.getAttribute('data-loaded') == '1') { continue; }
iframeSrc += '&fmt=' + encodeURIComponent(format);
iframeSrc += '&domid=' + encodeURIComponent(identifier);
var extElem = document.createElement('script');
extElem.setAttribute('type','text/javascript');
extElem.id = 'hzjs' + encodeURIComponent(identifier);
extElem.src = iframeSrc;
link.parentNode.appendChild(extElem);
} else {
var iframeElem = createIFrame(buttonWidth + (showCount?57:0), 20);
link.parentNode.replaceChild(iframeElem, link);
iframeElem.src = iframeSrc;
}
}
}
window.houzz = window.houzz || {};
window.houzz.processWidgets = processWidgets;
processWidgets();
})();
Any ideas about what's causing this?
This is because the script you are loading is getting all elements named a.
This will take HTML and SVG <a> elements without distinction.
The problem is that for SVG elements, the class attribute or className property is animatable. Which means that when you call a.className, you'll get an SVGAnimatedString Object, composed of two strings in two keys : baseVal and animVal.
Each of these keys has a split method, but not the SVGAnimatedString itself.
So the code should be modified to either find out if this is an HTML <a> (by checking its namespaceURI property), or to check if the split method is available before calling it, or by calling elem.getAttribute('class') instead of elem.className.
Hello Auto completion is not working well in my application.When we type a name it displays only a blank list[ Screenshots attached ].
Controller Code
public function list_UserByName($letters)
{
if(strpos($letters, ","))
{
$letters1 = explode(",",$letters);
$lecount = count($letters1);
$letters = $letters1[$lecount-1];
}
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
$response=$this->user_model->getAutoUserList($letters);
}
Model Code
public function getAutoUserList($letters)
{
$letters = preg_replace("/[^a-z0-9 ]/si","",$letters);
//AND user_type='C' AND user_status='A'
$query="select * from gm_users where uname Like '%$letters%'";
$result_query =$this->db->query($query);
foreach($result_query->result() as $result)
{
//echo "###".$result."|";
//$pinlevel =$this->functions->get_pinlevel($result->pinLevel);
//echo $result->userId."###".$result->uname." [ ".$pinlevel." ] "."|";
echo $result->userId."###".$result->uname."".$result->address." ".$result->city."|";
}
}
billing.php
<input type="text" autocomplete="off" size="20" name="txtname" id="txtname" onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);" value=""/>
ajax-dynamic-list.js
/************************************************************************************************************
(C) www.dhtmlgoodies.com, April 2006
This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.
Thank you!
www.dhtmlgoodies.com
Alf Magne Kalleland
************************************************************************************************************/
var ajaxBox_offsetX = 25;
var ajaxBox_offsetY = 5;
var ajax_list_externalFile = site_url+'/catalog/list_UserByName'; // Path to external file
var minimumLettersBeforeLookup = 1; // Number of letters entered before a lookup is performed.
var ajax_list_objects = new Array();
var ajax_list_cachedLists = new Array();
var ajax_list_activeInput = false;
var ajax_list_activeItem;
var ajax_list_optionDivFirstItem = false;
var ajax_list_currentLetters = new Array();
var ajax_optionDiv = false;
var ajax_optionDiv_iframe = false;
var ajax_list_MSIE = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)ajax_list_MSIE=true;
var currentListIndex = 0;
function ajax_getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop;
while((inputObj = inputObj.offsetParent) != null){
returnValue += inputObj.offsetTop;
}
return returnValue;
}
function ajax_list_cancelEvent()
{
return false;
}
function ajax_getLeftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue;
}
// Edited
function ajax_option_setValue_bkp(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
val = ajax_list_activeInput.value.split(',');
vals = '';
count = val.length - 1;
for(i=0;i<count;i++)
{
vals = vals + val[i] + ',';
}
ajax_list_activeInput.value = vals + tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_option_setValue(e,inputObj)
{
if(!inputObj)inputObj=this;
var tmpValue = inputObj.innerHTML;
//alert(inputObj.id);
document.getElementById('saleUserId').value=inputObj.id;
if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
if(!tmpValue)tmpValue = inputObj.innerHTML;
ajax_list_activeInput.value = tmpValue;
if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id;
ajax_options_hide();
}
function ajax_options_hide()
{
if(ajax_optionDiv)ajax_optionDiv.style.display='none';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='none';
}
function ajax_options_rollOverActiveItem(item,fromKeyBoard)
{
if(ajax_list_activeItem)ajax_list_activeItem.className='optionDiv';
item.className='optionDivSelected';
ajax_list_activeItem = item;
if(fromKeyBoard){
if(ajax_list_activeItem.offsetTop>ajax_optionDiv.offsetHeight){
ajax_optionDiv.scrollTop = ajax_list_activeItem.offsetTop - ajax_optionDiv.offsetHeight + ajax_list_activeItem.offsetHeight + 2 ;
}
if(ajax_list_activeItem.offsetTop<ajax_optionDiv.scrollTop)
{
ajax_optionDiv.scrollTop = 0;
}
}
}
function ajax_option_list_buildList(letters,paramToExternalFile)
{
ajax_optionDiv.innerHTML = '';
ajax_list_activeItem = false;
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length<=1){
ajax_options_hide();
return;
}
ajax_list_optionDivFirstItem = false;
var optionsAdded = false;
for(var no=0;no<ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length;no++){
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].length==0)continue;
optionsAdded = true;
var div = document.createElement('DIV');
var items = ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].split(/###/gi);
if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length==1 && ajax_list_activeInput.value == items[0]){
ajax_options_hide();
return;
}
div.innerHTML = items[items.length-1];
div.id = items[0];
div.className='optionDiv';
div.onmouseover = function(){ ajax_options_rollOverActiveItem(this,false) }
div.onclick = ajax_option_setValue;
if(!ajax_list_optionDivFirstItem)ajax_list_optionDivFirstItem = div;
ajax_optionDiv.appendChild(div);
}
if(optionsAdded){
ajax_optionDiv.style.display='block';
if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='';
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}
}
function ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,whichIndex)
{
if(whichIndex!=currentListIndex)return;
var letters = inputObj.value;
var content = ajax_list_objects[ajaxIndex].response;
var elements = content.split('|');
//alert(content);
ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()] = elements;
ajax_option_list_buildList(letters,paramToExternalFile);
}
function ajax_option_resize(inputObj)
{
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
}
function ajax_showOptions(inputObj,paramToExternalFile,e)
{
document.getElementById('saleUserId').value='';
if(e.keyCode==13 || e.keyCode==9)return;
if(ajax_list_currentLetters[inputObj.name]==inputObj.value)return;
if(!ajax_list_cachedLists[paramToExternalFile])ajax_list_cachedLists[paramToExternalFile] = new Array();
ajax_list_currentLetters[inputObj.name] = inputObj.value;
if(!ajax_optionDiv){
ajax_optionDiv = document.createElement('DIV');
ajax_optionDiv.id = 'ajax_listOfOptions';
document.body.appendChild(ajax_optionDiv);
if(ajax_list_MSIE){
ajax_optionDiv_iframe = document.createElement('IFRAME');
ajax_optionDiv_iframe.border='0';
ajax_optionDiv_iframe.style.width = ajax_optionDiv.clientWidth + 'px';
ajax_optionDiv_iframe.style.height = ajax_optionDiv.clientHeight + 'px';
ajax_optionDiv_iframe.id = 'ajax_listOfOptions_iframe';
document.body.appendChild(ajax_optionDiv_iframe);
}
var allInputs = document.getElementsByTagName('INPUT');
for(var no=0;no<allInputs.length;no++){
if(!allInputs[no].onkeyup)allInputs[no].onfocus = ajax_options_hide;
}
var allSelects = document.getElementsByTagName('SELECT');
for(var no=0;no<allSelects.length;no++){
allSelects[no].onfocus = ajax_options_hide;
}
var oldonkeydown=document.body.onkeydown;
if(typeof oldonkeydown!='function'){
document.body.onkeydown=ajax_option_keyNavigation;
}else{
document.body.onkeydown=function(){
oldonkeydown();
ajax_option_keyNavigation() ;}
}
var oldonresize=document.body.onresize;
if(typeof oldonresize!='function'){
document.body.onresize=function() {ajax_option_resize(inputObj); };
}else{
document.body.onresize=function(){oldonresize();
ajax_option_resize(inputObj) ;}
}
}
if(inputObj.value.length<minimumLettersBeforeLookup){
ajax_options_hide();
return;
}
ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
if(ajax_optionDiv_iframe){
ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;
}
ajax_list_activeInput = inputObj;
ajax_optionDiv.onselectstart = ajax_list_cancelEvent;
currentListIndex++;
if(ajax_list_cachedLists[paramToExternalFile][inputObj.value.toLowerCase()]){
ajax_option_list_buildList(inputObj.value,paramToExternalFile,currentListIndex);
}else{
var tmpIndex=currentListIndex/1;
ajax_optionDiv.innerHTML = '';
var ajaxIndex = ajax_list_objects.length;
ajax_list_objects[ajaxIndex] = new sack();
var search_key = inputObj.value.replace(" ","+");
//search_key1 = search_key.replace(",",",");
var url = ajax_list_externalFile + '/' +search_key;
ajax_list_objects[ajaxIndex].requestFile = url; // Specifying which file to get
ajax_list_objects[ajaxIndex].onCompletion = function(){ ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,tmpIndex); }; // Specify function that will be executed after file has been found
ajax_list_objects[ajaxIndex].runAJAX(); // Execute AJAX function
}
}
function wordcount(string) {
var a = string.split(/\s+/g); // split the sentence into an array of words
return a.length;
}
function ajax_option_keyNavigation(e)
{
if(document.all)e = event;
if(!ajax_optionDiv)return;
if(ajax_optionDiv.style.display=='none')return;
if(e.keyCode==38){ // Up arrow
if(!ajax_list_activeItem)return;
if(ajax_list_activeItem && !ajax_list_activeItem.previousSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.previousSibling,true);
}
if(e.keyCode==40){ // Down arrow
if(!ajax_list_activeItem){
ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
}else{
if(!ajax_list_activeItem.nextSibling)return;
ajax_options_rollOverActiveItem(ajax_list_activeItem.nextSibling,true);
}
}
/*if(e.keyCode==13 || e.keyCode==9){ // Enter key or tab key
if(ajax_list_activeItem && ajax_list_activeItem.className=='optionDivSelected')ajax_option_setValue(false,ajax_list_activeItem);
if(e.keyCode==13)return false; else return true;
}
if(e.keyCode==27){ // Escape key
ajax_options_hide();
}*/
}
//document.documentElement.onclick = autoHideList;
function autoHideList(e)
{
if(document.all)e = event;
if (e.target) source = e.target;
else if (e.srcElement) source = e.srcElement;
if (source.nodeType == 3) // defeat Safari bug
source = source.parentNode;
if(source.tagName.toLowerCase()!='input' && source.tagName.toLowerCase()!='textarea')ajax_options_hide();
}
Am a beginner in php as well as Codeigniter
Just echo your data in your controller
change
$response=$this->user_model->getAutoUserList($letters);
To
echo $this->user_model->getAutoUserList($letters);
change
onkeyup="ajax_showOptions(this,'getCountriesByLetters',event);
to
onkeyup="ajax_showOptions(this,'list_UserByName',event);
there is a question on this topic on stackoverflow, but an entire different process.
My Codeigniter autocomplete with ajax
I need to create data for a JSON request with the inputs taken from an html form. The data format that I want to generate is like below.
{
"applicationName":"Tesing",
"cpuCount":"12",
"hostdescName":"localhost",
"maxMemory":"0",
"maxWallTime":"0",
"minMemory":"0",
"nodeCount":"1",
"processorsPerNode":"12",
"serviceDesc":{
"inputParams":[
{
"dataType":"input",
"description":"my input",
"name":"myinput",
"type":"String"
},
{
"dataType":"input",
"description":"my input",
"name":"myinput",
"type":"String"
}
],
"outputParams":[
{
"dataType":"output",
"description":"my output",
"name":"myoutput",
"type":"String"
},
{
"dataType":"output",
"description":"my output",
"name":"myoutput",
"type":"String"
}
]
}
}
My code looks like below;
var jasonRequest = {};
jasonRequest["applicationName"] = appName;
jasonRequest["cpuCount"] = cpuCount;
jasonRequest["hostdescName"] = hostName;
jasonRequest["maxMemory"] = maxMemory;
jasonRequest["maxWallTime"] = ""; //TODO
jasonRequest["minMemory"] = ""; //TODO
jasonRequest["nodeCount"] = nodeCount;
jasonRequest["processorsPerNode"] = ""; //TODO
var inArray = new Array();
for(var j=0; j<inputCount; j++) {
var input = {};
input["dataType"] = "input";
input["description"] = "empty";
input["name"] = $("#inputName" + j+1).val();
input["type"] = $("#inputType" + j+1).val();
inArray[j] = input;
}
var outArray = new Array();
for(var j=0; j<outputCount; j++) {
var output = {};
output["dataType"] = "output";
output["description"] = "empty";
output["name"] = $("#outputName" + j+1).val();
output["type"] = $("#outputType" + j+1).val();
outArray[j] = output;
}
var serviceDesc = {};
serviceDesc["inputParams"] = inArray;
serviceDesc["outputParams"] = outArray;
jasonRequest["serviceDesc"] = serviceDesc;
alert("printing inArray");
alert(inArray.toSource().toString());
alert(JSON.stringify(jasonRequest));
The data created by this code is like below. I could use strings and create the message by concatenating it but I don't think that is a nice way of doing this. As you can see the inputParams and outputParams are not properly populated. Can you suggest how can I properly generate this message.
{
"applicationName":"Tesing",
"cpuCount":"12",
"hostdescName":"localhost",
"maxMemory":"0",
"maxWallTime":"0",
"minMemory":"0",
"nodeCount":"1",
"processorsPerNode":"12",
"serviceDesc":{"inputParams":"","outputParams":[]}}
[EDIT]
My code looks like below.
$(document).ready(function(){
var inputCount = 0;
var outputCount = 0;
$("p1").live("click", function(){
inputCount++;
$(this).after("<br/>");
$(this).after("Input Name *:" +
"<input type="text" id="inputName" + inputCount + "" name="inputName" + inputCount + "" value="echo_input" size="50"><br/>");
$(this).after("Input Type *:" +
"<input type="text" id="inputType" + inputCount + "" name="inputType" + inputCount + "" value="String" size="50"><br/>");
});
$("p2").live("click", function(){
$(this).after("Output Name *:" +
"<input type="text" id="outputName" + outputCount + "" name="outputName" + outputCount + "" value="echo_output" size="50"><br/>");
$(this).after();
$(this).after("Output Type *:" +
"<input type="text" id="outputType" + outputCount + "" name="outputType" + outputCount + "" value="String" size="50"><br/>");
});
$('[name="btn2"]').click(function(){
var appName = $("#appName1").val();
var exeuctableLocation = $("#exeuctableLocation1").val();
var scratchWorkingDirectory = $("#scratchWorkingDirectory1").val();
var hostName = $("#hostName1").val();
var projAccNumber = $("#projAccNumber1").val();
var queueName = $("#queueName1").val();
var cpuCount = $("#cpuCount1").val();
var nodeCount = $("#nodeCount1").val();
var maxMemory = $("#maxMemory1").val();
var serviceName = $("#serviceName1").val();
var inputName1 = $("#inputName1").val();
var inputType1 = $("#inputType1").val();
var outputName = $("#outputName1").val();
var outputType = $("#outputType1").val();
var jsonRequest = {};
jsonRequest["applicationName"] = appName;
jsonRequest["cpuCount"] = cpuCount;
jsonRequest["hostdescName"] = hostName;
jsonRequest["maxMemory"] = maxMemory;
jsonRequest["maxWallTime"] = ""; //TODO
jsonRequest["minMemory"] = ""; //TODO
jsonRequest["nodeCount"] = nodeCount;
jsonRequest["processorsPerNode"] = ""; //TODO
var inArray = [];
for(var j=0; j<inputCount; j++) {
var input = {};
input["dataType"] = "input";
input["description"] = "empty";
input["name"] = $("#inputName" + j+1).val();
input["type"] = $("#inputType" + j+1).val();
inArray[j] = input;
}
var outArray = new Array();
for(var j=0; j<outputCount; j++) {
var output = {};
output["dataType"] = "output";
output["description"] = "empty";
output["name"] = $("#outputName" + j+1).val();
output["type"] = $("#outputType" + j+1).val();
outArray[j] = output;
}
var serviceDesc = {};
serviceDesc["inputParams"] = inArray;
serviceDesc["outputParams"] = outArray;
jsonRequest["serviceDesc"] = serviceDesc;
alert("printing inArray");
alert(inArray.toSource().toString());
alert(JSON.stringify(jsonRequest));
$.ajax({
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://localhost:7080/airavata-registry-rest-services/registry/api/applicationdescriptor/build/save/test",
data: jasonRequest
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
What's inputCount and outputCount? Seems like they are zero or NaN or something, so you get empty arrays. Yet, your code will still print "inputParams":[] instead of "inputParams":"".
To get a nice output (not that it would be needed for your app, only for debugging), you can use the third parameter of JSON.stringify.