Let me share my jQuery part first
$(".btnUpdateInput").click(function() {
//alert("Update");
var BldDocumentId = $("#BldDocId").val();
var BldinstructionId = $("#BldIPInstnId").val();
var InputFieldId = $("#InputFieldId").val();
var InputFieldValue = jQuery.trim($(this).parent().prev().text()); //$("#InputFieldValue").val();
var InputFieldUserValue = jQuery.trim($(this).prev().val()); // $(".user_input_value").val();
alert(BldDocumentId + "," + BldinstructionId + "," + InputFieldId + "," + InputFieldValue + "," + InputFieldUserValue);
var postResult;
alert($(this).get());
$.post("/Build/UpdateInputField",
{ bldDocId: BldDocumentId, bldInstnId: BldinstructionId, inputFieldId: InputFieldId, inputFieldValue: InputFieldValue, inputFieldUserValue: InputFieldUserValue },
function(result) {
postResult = result;
//Either this should function**
alert($(this).get()); // returned Object[Object] but expected the clicked button
alert($(this).parent().get());// returned null
alert($(this).parent().next().get());//returned null
alert($(this).parent().next().children().first().get());// returned null
// $(this).parent().next().show();
// $(this).parent().next().children().first().text(InputFieldUserValue);
// $(this).parent().hide();
});
alert(postResult);
//Or this should function**
if (postResult == true) {
$(this).parent().next().show();
$(this).parent().next().children().first().text(InputFieldUserValue);
$(this).parent().hide();
}
});
Now let me explain my issue. I need to show and hide few divs with respect to the button "btnUpdateInput" I clicked. I tried it in two ways: 1. I gave the following lines in the in the success part of $.post
$.post("/Build/UpdateInputField",
{ bldDocId: BldDocumentId, bldInstnId: BldinstructionId, inputFieldId: InputFieldId, inputFieldValue: InputFieldValue, inputFieldUserValue: InputFieldUserValue },
function(result) {
postResult = result;
//Either this should function**
alert($(this).get()); // returned Object[Object] but expected the clicked button
alert($(this).parent().get());// returned null
alert($(this).parent().next().get());//returned null
alert($(this).parent().next().children().first().get());// returned null
// $(this).parent().next().show();
// $(this).parent().next().children().first().text(InputFieldUserValue);
// $(this).parent().hide();
});
2. or get the value of postResult out and compare and do the same there. The code is bellow:
if (postResult == true) {
$(this).parent().next().show();
$(this).parent().next().children().first().text(InputFieldUserValue);
$(this).parent().hide();
}
Neither works for me. In 1 am not getting $(this) as the button 'btnUpdateInput' that i click and 2. the value of postResult is undefined since there is no delay so that postResult is assigned to result of post action.
Please help me out with either of the scenario.
This is the element in your current IN. So in the SUCCES its in the return.
So in method one you could do:
$(".btnUpdateInput").click(function(e) {
var self = e;
//code
alert($(self).get()); // returned Object[Object] but expected the clicked button
alert($(self).parent().get());// returned null
alert($(self).parent().next().get());//returned null
alert($(self).parent().next().children().first().get());// returned null
}
Seems self is also used as default....
Try this instead:
$(".btnUpdateInput").click(function(e) {
var myButton = $(this);
//code
alert($(myButton).get()); // returned Object[Object] but expected the clicked button
alert($(myButton).parent().get());// returned null
alert($(myButton).parent().next().get());//returned null
alert($(myButton).parent().next().children().first().get());// returned null
}
Related
I'm creating a var where I want to assign it to a var that I get from another entity
function SubmitAction(executionContext) {
var lookupItem = formContext.getAttribute("alfa_member").getValue()[0].id;
var theTotalMembersTravling = formContext.getAttribute("alfa_numberofdependent").getValue();
var remainFlightCredit;
debugger;
Xrm.WebApi.online.retrieveRecord("contact",lookupItem, "?$select=new_remainstravelcredit").then(
function employessPackage(result) {
var new_remainstravelcredit = result["new_remainstravelcredit"];
if(new_remainstravelcredit !== null){
if(new_remainstravelcredit > 0)
{
remainFlightCredit = new_remainstravelcredit;
console.log(remainFlightCredit+" This not inside any if condition");
var newRemain = (parseInt(remainFlightCredit)) - (parseInt(theTotalMembersTravling));
console.log(newRemain+ " This in the remain if condition");
var entity = {};
entity.new_remainstravelcredit = newRemain.toString();
Xrm.WebApi.online.updateRecord("contact",lookupItem, entity).then(
function success(result) {
var updatedEntityId = result.id;
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);
} if(new_remainstravelcredit <= 0)
{
Xrm.Utility.alertDialog("You have exceeds the travel credit");
console.log(remainFlightCredit);
}
}
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);
console.log(remainFlightCredit);
}
So as result in this line
remainFlightCredit = new_remainstravelcredit;
console.log(remainFlightCredit+" This not inside any if condition");
Which inside the webapi call I'm able to get the value but outside in the main function at the end when I write
console.log(remainFlightCredit);
I'm unable to get the value remainFlightCredit, do you have any suggestions to solve this issue?
This is expected behavior, as this is a promise call (asynchronous) the code outside the main api call will execute before the success callback function employessPackage.
So remainFlightCredit value get assigned after the last console.log line in your code.
You can place a breakpoint to debug and see it in action.
I'm using the function below to validate several input fields on a web form. The function iterates through the fields using jQuery .each() iteration. The ValidateInput function validates each individal input field, returning a true or false.
function ValidateForm() {
var result = true;
$('[data-regex]').each(function() {
result = result && ValidateInput(this);
// return true;
});
if ( result == false ) {
$(".alert").show();
}
return result;
}
The problem I'm having is that the .each() is terminating early, as soon as any individual input field fails validation. I know that if function() returns false, the .each() will terminate, but I don't see how I'm doing that. I've even tried adding an explicit return true; as the last line of function(), but this made no difference.
For completeness, here's ValidateInput:
function ValidateInput(thisInput) {
var fieldName = $(thisInput).attr('name');
var fieldValue = $(thisInput).val();
var regex = $(thisInput).attr('data-regex');
console.log('validating field "' + fieldName + '" value "' + fieldValue + '" with regEx "' + regex + '"';
var re = new RegExp(regex);
var result = re.test(fieldValue);
if ( result ) {
console.log('- passed');
$(thisInput.closest(".form-group")).addClass("has-success").addClass("has-feedback")
} else {
console.log('- failed');
$(thisInput.closest(".form-group")).addClass("has-error").addClass("has-feedback")
};
return result;
}
The code that calls ValidateForm is as follows:
<input type="submit" name="ct108" value="Save User" onclick="return ValidateForm();" />
What am I missing?
Your ValidateInput method stops processing after the first one that doesn't pass validation because this line:
result = result && ValidateInput(this);
The way && works is that if the item on the left side is truthy the value on the right is returned as the value, otherwise the value on the left is returned as the value.
You can guarantee that each one is processed by flipping it around:
result = ValidateInput(this) && result;
I'm trying to write a Parse.com Cloud Code function to accomplish the following workflow:
User submits a value.
Cloud code function checks to see if that value matches any objects of type code.
If not, the function returns a "not found" value.
If so, the object of type code is assumed to have a pointer to an object of type item.
Then, code.item is checked to see whether it has a pointer to an object of type alert.
If not, the function returns a "not found" value.
If code.item.alert does exist, then I want to fetch the full alert object, including pointers which may or may not exist, up to 2 layers deep.
As I begin writing the code for this function, I can get it working to the point of checking to see whether the code exists and, if so, whether code.item.alert also exists.
This is where the problem arises. As it currently stands, in the working version of my function, the alert item that is returned is only the class type and objectId. I understand why that is happening, and I am trying to write code to populate the object before returning it, but I am failing in that attempt.
Here's the code that is working so far (but only returning the alert object's shell):
Parse.Cloud.define("alertLookup", function (request, response) {
Parse.Cloud.useMasterKey();
var codeQuery = new Parse.Query("code");
codeQuery.equalTo("value", request.params.code);
codeQuery.include("item");
codeQuery.find().then(function (codes) {
if (codes.length === 0) {
response.success("no item");
} else {
var code = codes[0];
var item = code.get("item");
var alert = item.get("alert");
if (alert === null || alert === undefined) {
response.success("no item");
} else {
response.success(alert);
}
}
}, function (error) {
response.error(error);
});
});
Here's what I have tried that is failing with an error code of 141:
Parse.Cloud.define("alertLookup", function (request, response) {
Parse.Cloud.useMasterKey();
var codeQuery = new Parse.Query("code");
codeQuery.equalTo("value", request.params.code);
codeQuery.include("item");
codeQuery.find().then(function (codes) {
if (codes.length === 0) {
response.success("no item");
} else {
var code = codes[0];
var item = code.get("item");
var alert = item.get("alert");
if (alert === null || alert === undefined) {
response.success("no item");
} else {
return alert.fetch();
}
}
}).then(function (a) {
response.success(a);
}, function (error) {
response.error(error);
});
});
Why won't the fetch() call work properly? When I insert console.log() statements, although alert is non-null, return alert.fetch(); does not ever seem to be called. At least, the response.success(a); line is never called. Why not?
Try this instead while chaining Promises:
codeQuery.find().then(function (codes) {
if (codes.length != 0) {
var code = codes[0];
var item = code.get("item");
var alert = item.get("alert");
if (alert != null && alert != undefined) {
var alertObj = new Parse.Object("alert"); // alert class ???
alertObj.id = alert.id;
return alertObj.fetch();
}
}
// return a Promise for no items
return Parse.Promise.as("no item");
}).then(function (a) {
response.success(a);
}, function (error) {
response.error(error);
});
I have a very strange issue that I am running into. I am using jsTree from JQueryUI on one of my sites, and I have different implementations of it used in different .js files. One of them seems to work, which is very confusing as it uses almost identical code (only the variable names are different) to the implementation that is broken. The problem comes from the contextmenu function. The code I am using is as follows:
$(document).ready(function () {
if(typeof dryerList == 'undefined' || dryerList.length == 0) {
var dryerList = [];
$.ajax({
url:'../TrackingApp/getGrainBins.php?t=234.23423452353',
async: false,
success: function(text) {
try {
dryerList = $.parseJSON(text);
} catch (e) {
alert('ERROR: ' + e);
}
if(dryerList.length == 0) {
alert('ERROR: No fleet data received.')
}
}
});
}
$("#dryerListTree").jstree({
plugins : ['json_data', 'ui', 'themes', 'contextmenu'],
contextmenu: {items: customBinMenu},
json_data : { data: binNodes }
});
$('#dryerListTree').bind("dblclick.jstree", function (event) {
var node = $(event.target).closest("li");
var id = node[0].id;
for(i=0; i < dryerList.length; i++) {
if(id == dryerList[i].id) {
centerMap(dryerList[i].y, dryerList[i].x);
break;
}
}
});
});
function customBinMenu(node) {
if ($(node).hasClass("folder")) {
return;
}
var items = {
centerItem: {
label: "Locate",
action: function () {
// Centers map on selected bin
var id = node[0].id;
for(i=0; i < dryerList.length; i++) {
if(id == dryerList[i].id) {
centerMap(dryerList[i].y, dryerList[i].x);
break;
}
}
}
},
dashboardItem: {
label: "Dashboard",
action: function () {
// Opens dryer info window over map
var id = node[0].id;
var dryerIndex = -1;
for(i=0; i < dryerList.length; i++) {
if(id == dryerList[i].id) {
dryerIndex = i;
break;
}
}
}
}
};
return items;
}
The strange bit is, the double-click handler works just fine. When I get to the customBinMenu() function, the dryerList array is there, and dryerList[0] contains 4 of the 5 values that it should- but somehow the 'id' element has been dropped from that object. I have been looking at this for quite some time, and I can't figure out how it can drop a single element from the object without losing any other data, especially when identical code is working for a similar list. Any suggestions?
Ok, I read in your question: 'and dryerList[0] contains 4 of the 5 values that it should- but somehow the 'id' element has been dropped from that object'
So by 'element' and 'value' I assume you mean 'attribute': the node's 'id'-attribute to be precise ??
I see in your code: var id = node[0].id;
That should be: var id = node[0].getAttribute("id");
Good luck!
UPDATE 1:
Ok, if (as per your comment) var id = node[0].id; (getting id from node[0]) is ok, then if(id == dryerList[i].id) looks wrong, since you just (re-)defined id to be the value of node[0]'s id.
Actually I would not use 'id' as a var-name (in this case).
So what if you did: var idc = node[0].getAttribute("id");
and then: if(idc === dryerList[i].getAttribute("id"))
UPDATE 5: You still have some errors by the way:
You forgot a semi-colon to close the alert in:
if(dryerList.length == 0) {
alert('ERROR: No fleet data received.')
}
You should use '===' to compare with '0' on line 2 and 14
naturally in real life you would define function customBinMenu(node) before it was used in your document.ready function.
Fixed by swapping code order.
The same goes for this document.ready function where you used var dryerList before it was defined.
Fixed by: var dryerList = dryerList || []; if(dryerList.length === 0){//ajax & json code}
Could you please confirm if this fiddle, which is now valid javascript, represents your intended baseline-code that still results in your problem of the 'id'-attribute being 'undefined' in dryerList's node-collection (since the code you posted contained some simple errors that are fixed in this jsfiddle, excluding the things mentioned in update 1, since you commented that this is not the problem) ?
May I ask (since you start at document.ready), why do you (still) check if dryerList already exists?
May I ask if you could update that corrected fiddle with some demo-data for us to toy around with?
I am creating an object to handle the YouTube API and I have two methods:
getCommentList - getting a url for the current upload,for example http://gdata.youtube.com/feeds/api/videos/VIDEO_ID/comments?alt=json and return an array of objects - author of the comment and the content of the comment.
getEntriesObject - returning an array with objects for each upload entry we have title,thumbnail,and the comment list that returned from getCommentList
My jQuery code:
var Youtube = {
getCommentObject : function(url){
if( url ){
var currentCommentFeed = {},
commentsList = [];
$.getJSON(url,function(data){
$.each(data.feed.entry,function(index){
currentCommentFeed = this;
commentsList.push({
author : currentCommentFeed.author[0].name.$t,
content : currentCommentFeed.content.$t
});
});
return commentsList;
});
}
},
getEntriesObject : function(){
var username = 'SOMEYOUTUBEUSERHERE',
url = 'http://gdata.youtube.com/feeds/api/users/' + username + '/uploads?alt=json',
currentEntry = {},
currentObject = {},
entryList = [];
// Scope fix
var that = this;
$.getJSON(url,function(data){
$.each(data.feed.entry, function(index){
// Caching our entry
currentEntry = this;
// Adding our entry title and thumbnail
currentObject = {
title: currentEntry.title.$t
};
if(currentEntry.media$group.media$thumbnail.length == 4)
currentObject['thumbnail'] = currentEntry.media$group.media$thumbnail[3].url;
// Let`s get the comments - undefined....
currentObject['comments'] = that.getCommentObject(currentEntry.gd$comments.gd$feedLink.href + "?alt=json");
console.log(currentObject);
entryList.push(currentObject);
});
});
return entryList;
}
/*
entry[i].title.$t
entry[i].gd$comments.gd$feedLink.href + "?alt=json"
entry[i].media$group.media$thumbnail[3]
// Comments
entry[i].author.name.$t
entry[i].author.content.$t
*/
};
I have console.log(currentObject) and am getting the title. But am not getting the thumbnail URL and the comments.
In addition, when I run getEntriesObject I get back an empty array.
When you call return in the callback to $.getJSON you are returning only that callback function, not the "outer" getCommentObject. Thus when you later call that.getCommentObject you're not getting anything in return (undefined).
getCommentObject: function(url){
if( url ){
// Snip ...
$.getJSON(url,function(data){
// Snip ...
return commentsList; // <- Here
});
}
}
To amend this make getCommentObject take a callback function.
getCommentObject: function(url, callback){
if( url ){
// Snip ...
$.getJSON(url,function(data){
// Snip
// Remove the return statement
callback(commentsList);
});
}
}
Call this function like this:
that.getCommentObject(
currentEntry.gd$comments.gd$feedLink.href + "?alt=json",
function (commentsList) {
currentObject['comments'] = commentsList;
});
Replacing
currentObject['comments'] = that.getCommentObject(currentEntry.gd$comments.gd$feedLink.href + "?alt=json");
You are getting the empty comments because the return statement is in the wrong place. It is in the getJSON callback function. You need to move it from line no 19 to 21 so that it becomes the return statement for getCommentObject. This will fix the first problem. (comments undefined)
Second getEntriesObject is empty because, for some users youtube is returning "Service Unavailable" error for the json request. This happened for when I tried with some random username on youtube.
I checked your program with youtube username "google". After changing the return statement it worked fine.
Hope this helps.