JQuery / JS - change: function issues with single characters - javascript

My Autocomplete with Ajax works extremely well providing everything I need for the most part, however a small issue arises when intended input is just a single character.
I have implemented this for several other text fields the same way without issues, however this is the only section that has potential one character input.
In case anyone wonders the Stored procedure from the url is rock solid, just having issues with my Javascript and how to handle/compare the data.
This is being used in a .net 5 web application but should not matter in this context.
The hardcoded if statement is my current work around, when I remove it I get the standard
TypeError: Cannot read properties of undefined (reading 'toLowerCase')
Looking at the console it seems to print only the last window.item (cList) from the list rather than a full list, perhaps I need to store the whole list and loop it? I tried to raise min value from 1 to 2 for the Autocomplete to avoid double character items but it doesn't help.
It only sees the input "1" on one of the four console logs below when it should realistically show for all four.
undefined Hardcoded match
1 Hardcoded match
Code1 match
Code1 match
$("#hahSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '/stationData/searchHACode',
headers: {
"RequestVerificationToken":
$('input[name="__RequestVerificationToken"]').val()
},
data: { "term2": request.term },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
window.list = item;
return item;
}))
},
error: function (xhr, textStatus, error) {
alert(xhr.statusText);
},
failure: function (response) {
alert("failure " + response.responseText);
}
});
},
change: function (event, ui) {
var cList = window.list;
//var cListLength = cList.length;
var input = $("#hahSearch").val()
if (input == 1 || input == 2 || input == 3 || input == 5 || input == 9 ) {
console.log(cList + " Hardcoded match");
console.log(input + " Hardcoded match");
$(this).css('background-color', '#b8f4b8');
cList = "";
input = "";
}
if (input.toLowerCase() == cList.toLowerCase() || ui.item) {
console.log(cList + " Code1 match");
console.log(input + " Code1 match");
$(this).css('background-color', '#b8f4b8');
cList = "";
input = "";
}
else if (input.toLowerCase() != cList.toLowerCase() && !ui.item) {
console.log(cList + " Code1 no match");
console.log(input + " Code1 no match");
$(this).css('background-color', '#ff6347');
$(this).val('');
cList = "";
input = "";
}
},
minLength: 2
});

Related

Dynamics CRM 2016 Javascript forEach not supported

So I am trying to write javascript code for a ribbon button in Dynamics CRM 2016 that will grab a phone number from a list of Leads that can be seen in the Active Leads window.
However, when I try to run it, I get an error telling me
As I step into my code (I'm debugging), I see this error
Here is the code I am working with.
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
// this should iterate through the list
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
//this should get the id and name of the selected lead
getPhoneNumber(selected, SelectedEntityTypeName);
});
}
//I should have the lead ID and Name here, but it is returning null
function getPhoneNumber(id, entityName) {
var query = "telephone1";
Sdk.WebApi.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
// I'm trying to capture the number and display it via alert.
alert(telephone1);
},
function (error) {
alert(error);
})
}
Any help is appreciated.
What you have is an javascript error. In js you can only use forEach on an array. SelectedControlSelectedItemIds is an object not an array.
To loop though an object, you can do the following.
for (var key in SelectedControlSelectedItemIds){
if(SelectedControlSelectedItemIds.hasOwnProperty(key)){
getPhoneNumber(SelectedControlSelectedItemIds[key], SelectedEntityTypeName)
}
}
Okay, so I figured it out. I had help, so I refuse to take full credit.
First, I had to download the SDK.WEBAPI.
I then had to add the webAPI to my Javascript Actions in the Ribbon Tool Bench.
Then, I had to create a function to remove the brackets around the
SelectedControlSelectedItemIds
Firstly, I had to use the API WITH the forEach method in order for it to work.
These are the revisions to my code.
function removeBraces(str) {
str = str.replace(/[{}]/g, "");
return str;
}
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
//alert(SelectedEntityTypeName);
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
getPhoneNumber(removeBraces(selected), SelectedEntityTypeName);
// alert(selected);
});
}
function getPhoneNumber(id, entityName) {
var query = "telephone1";
SDK.WEBAPI.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
formatted = telephone1.replace(/[- )(]/g,'');
dialready = "1" + formatted;
withcolon = dialready.replace(/(.{1})/g,"$1:")
number = telephone1;
if (Xrm.Page.context.getUserName() == "Jerry Ryback") {
url = "http://111.222.333.444/cgi-bin/api-send_key";
} else if(Xrm.Page.context.getUserName() == "Frank Jane") {
url = "http://222.333.444.555/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bob Gilfred"){
url = "http://333.444.555.666/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Cheryl Bradley"){
url = "http://444.555.666.777/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bill Dunny"){
url = "http://555.666.777.888/cgi-bin/api-send_key";
}
if (url != "") {
var params = "passcode=admin&keys=" + withcolon + "SEND";
var http = new XMLHttpRequest();
http.open("GET", url + "?" + params, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
}
},
function (error) {
// alert(error);
})
}
To elaborate, once I successfully get the number, I remove the parenthesis, dashes and white-space. Then, I add a "1" to the beginning. Finally, I insert colons in between each number. Then, I create an HTTP command and send it to the office phone of whoever is using CRM at the time. The user eval and HTTP message is my code. I'm showing you all of this because it was a great learning experience, and this feature really adds to the functionality.
I hope some of you find this useful.
Thanks for the help.

If condition not working if (str == "1") while data is returning 1

If condition not working while data is returning 1 and 0 but it always execute the else code, i am unable to find error, code is working fine on localhot but not on server
$('#by_head_name').on('blur', function() {
var headsubt = document.getElementById('by_head_name').value;
if (headsubt !== "") {
//alert('hi');
$.post('verify-head-or-subhead-name.php', {
headsub: headsubt
},
function(data, status) {
var str = data;
if (str == "1") {
var headd = "ok";
alert('ok');
} else if (str == "0") {
alert("No Head Exist, Please choose valid Head or create one before selecting it");
} else {
alert(data);
this.value == '';
}
});
}
Please check what "data" of the success function returns in your alert message.
If it returns string directly, then your condition should work.
If it shows object in the alert screen, please verify your object and accordingly choose a variable which satisfy your condition like data.value.

variable is not getting defined even though the code works somwhere else

so i am building a game in three js and trying to make it multiplayer throught socket.io so i am loading all of my characters into an array called players on my server side
and then i pass it to each client when they connect like so
socket.on('addPlayer', function(username) {
players.push(username)
console.log(username + " joined")
console.log("online Users " + players)
socket.broadcast.emit('syncPlayers', players)
socket.emit('syncPlayers', players)
})
and on my client syncPlayers looks like this
socket.on('syncPlayers', function(players) {
players.forEach(function(value) {
if (value == username) {
console.log("not adding " + value + " thats you ")
loadPlayerdata(username)
} else {
console.log("player Online " + value);
newplayer = value;
loadPlayerdata(newplayer)
addPlayer(newplayer)
}
});
})
then it calls this wich sends the server data
function loadPlayerdata(playerName) {
console.log(playerName)
console.log("phase1")
socket.emit('loadPlayerdata', playerName)
}
then this is called and it retrieved the player name and the data of the players location this is were my problem lies
socket.on('loadPlayerdata', function(data, username) {
toMove = threeObjects[username + "Char"]
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
console.log(toMove)
toMove.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
}
i keep getting Uncaught TypeError: Cannot read property 'position' of undefined
even though i can use this
function addPlayer(playerName) {
var charObjectName = playerName + "Char"
var threeObject = models.tent1.mesh.clone();
scene.add(threeObject)
//threeObject.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
// set reference
threeObjects[charObjectName] = threeObject;
}
btw i have an object
var threeObjects = {};
can someone please explain why it wont work and how to fix it
You can read this answer to understand the difference between dot and brackets notation.
You are getting error because, tomove seems to be undefined and dot notation will throw error if any new user joins and if the object is empty.
Check if this helps. This will assign the object key as username and position as an value which will be array like this,
{"usernamechar": {"position": [x,y,z]}}
socket.on('loadPlayerdata', function(data, username) {
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
threeObjects[username + "Char"]["position"] = [world.spawnPointx, world.spawnPointy, world.spawnPointz]
}
}

IF-ELSE statement not working

I'm trying my best to create a website.
I need to create an IF-ELSE in ajax. It basically calls the content of an input called "greeting" and aims at writing "YES" if the user inserts a specific text and "NO" otherwise.
jQuery(document).ready(function () {
var greeting = jQuery("#greeting").val();
jQuery("#push-me").click(function () {
jQuery.ajax({
type: 'POST',
url: 'http://www.boatsandbeats.com/wordpress/wp-admin/admin-ajax.php',
data: {
action: 'myAjax',
greeting: jQuery("#greeting").val(),
},
success: function (data, textStatus, XMLHttpRequest) {
if (data == "XYZ") == 0 {
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
} else {
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
While the rest of the code works just fine, it does not recognize the IF and takes everything as if it were true (therefore, printing "YES").
Can anybody be so kind and explain this to me?
it is not working because your if statement is wrong
if (data == "XYZ") == 0 {
should be
if (data.greeting == "XYZ") {
}
Step 1: check if your ajax actually returns something.
...//add the following line
success: function (data, textStatus, XMLHttpRequest) {
console.log(data);
alert("Data logged." + data);
...
Step 2: what do you want to test?
You want to know if data (the ajax return) is a string and that string is having the value "XYZ"?
//change
if (data == "XYZ") == 0
//to
if (data === "XYZ")
Note the triple === it's not the same as ==. The difference is that === will check if the variables have the same value and the same type.
In addition, in Javascrip can compare string similar to your style like using localeCompare():
if (data.localeCompare("XYZ") === 0)
/* strA.localeCompare(strB); Returns:
0: exact match
-1: strA < strB
1: strB > strA
*/
UPDATE:
Assuming your php function is as the following:
function myAjax()
{
$greeting = $_POST['greeting'];
if (isset($_POST['greeting']))
$greeting = $_POST['greeting'];
$results = "<h2>".$greeting."</h2>";
die($results);
}
This is what's going to happen.
{
//$greeting is being assigned a value from POST greetings, // in post is empty then $greeting will be empty as well.
$greeting = $_POST['greeting'];
//You are validating POST greeting, although you already captured it's value and put it in $greeting, so why not using $greeting here instead?
if (isset($_POST['greeting']))// this if has no {} so ONLY the first line after will be included in this IF condition.
$greeting = $_POST['greeting'];
// this line will be exectue no matter what, so the value of $greeting will be entered into a string enclosed with <h2> tags. if POST greeting is empty, then $greeting will be empty of course.
$results = "<h2>" . $greeting . "</h2>";
//the variable $result now has "<h2></h2>" as it's value if $greeting is empty.
die($results); //echoing $result, or
}
So, since you have confirmed that you are receiving "" as a value for data variable returned from AJAX. Why are you comparing it to XYZ in your condition?
In your JS you are assigning "#greeting").val() to a variable greeting, then you use that variable as an array attribute for your ajax{data{greeting:jQuery("#greeting").val() }}
var greeting = jQuery("#greeting").val();// what is the use of this line?
Enclose your object attribute with "" e.g. "greeting".
data: {
"action": 'myAjax',
"greeting": jQuery("#greeting").val(),// what is the value of "#greeting").val()?
},
first of all you need to check data will exactly print XYZ or print [Object object]
if [Object object] then you need to check data.d=="XYZ"
in success function first parse then compare like this
var response=$.parseJSON(data);
if(response.field=="XYZ")
{
jQuery("#test-div").html('');
jQuery("#test-div").append("YES");
}
else
{
jQuery("#test-div").html('');
jQuery("#test-div").append("NOPE");
}
IF condition system is looks wrong,
if (data == "XYZ") == 0
You should use only, no need == 0
if (data == "XYZ"){
//.... code here
}
OR If ajax response in json
if (data.key == "XYZ"){
//.... code here
}

Why is my loop of JSON setting values?

I'm really sorry to be posting all day. I'm a total newbie with this coding. Basically, with the help of a lot of amazing people here, I'm setting up a JSON thingy for the first time. I'm trying to evaluate a list against an input. Here's sample data:
{
"
films": [{
"label": "34",
"value": "34",
"currently_streaming": "1",
"full_streaming_url": "http://www.url.com",
"url": "http://www.url.com"},
{
"label": "A Different Color",
"value": "A Different Color",
"currently_streaming": "1",
"full_streaming_url": "http://www.url.php",
"url": "http://www.url.com"}]
}​
and here's my code. I finally got it, (thank you everyone!) to select the value portion that I wanted. I then tried to compare it in an if/else statement, and it's doing weird things. First, it seems to be pulling more values than actually exist on the file, but I'm not completely sure about that. Secondly, however, it seems to be not comparing values, but setting one the value I'm iterating through equal to another value! I don't understand!
var test = "34x25x36";
$(document).ready(function () {
$.ajax({
dataType: 'json',
beforeSend: function () {
console.log('Before Ajax Request Starts !!');
},
success: function (data) {
console.log(data);
alert("Edddddddd");
$.each(data.films, function (i, object) {
$.each(object, function (property, value) {
//alert(property + "=" + value);
for (i = 0; i < data.films.length; i++) {
var theFilm = (data.films[i].value);
if (theFilm == test) {
document.write(theFilm);
document.write(test + "<br>");
} else {}
}
});
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error occurred: " + errorThrown);
},
beforeSend: function () {
console.log('Ajax Request Complete !!');
},
url: 'test.php'
});
});
EDIT
When I do have something in the else{ } section, it seems to run the whole thing multiple times, judging correctly when doesn't match, but then it seems to run again, running the text for the one match and then a bunch of "not match" text. When there is nothing in the else{} section, it seems to set the value of theFilm = test . Help!
your success function is messed up.. Look's like you are getting confused by using many loops..
Also do not write it to a document.. Use console.log or alert to debug..
Try this approach
success: function(data) {
console.log(data);
alert("Edddddddd");
var keys = ["label", "value", "currently_streaming", "full_streaming_url", "url"]
for (i = 0; i < data.films.length; i++) {
for (j = 0; j < keys.length; j++) {
// alert('Key - ' + keys[j] + ' :: Value - ' + data.films[i][keys[j]]);
var theFilm = data.films[i][keys[j]];
if (theFilm == test) {
alert('TheFilm Variable is : ' + theFilm);
alert('Test Variable is : ' + test );
}
else {
alert('No Match Found !!');
}
}
}
}​
You are looping through all films, and then inside that you are looping through all properties of each film. Then inside that you are looping through all films again. That's a lot of looping for no reason. If you have for example 100 films with 5 properties in each, you will be looping through all the films 500 times, thus writing out the film that you find 500 times.
You only need one loop to loop through the films and find one:
$.each(data.films, function(i, object) {
var theFilm = object.value;
if (theFilm == test) {
document.write(theFilm);
}
});
Demo: http://jsfiddle.net/baJtf/
You can also use the grep method to find items in an array:
var film = $.grep(data.films, function(f){
return f.value == test;
});
if (film.length == 1) {
document.write(film[0].value);
}
Demo: http://jsfiddle.net/baJtf/1/

Categories

Resources