Here I want to check the match for the particular class name (last class with the name of YtoD) and write a condition according to it. I have not Idea why it is not working.
HTML:
Select Range: Last Month | Last 2 Weeks | Last 1 Week| Year to Date
Javascript
function Lab(obj) {
var a = obj.name;
if (a != YtoD) {
document.getElementById("linechartxaxislabel").innerHTML = "Price
Timeline" + "(Last" + a + ")";
} else {
document.getElementById("linechartxaxislabel").innerHTML = "Year
to Date";
}
}
What should I do here?
Try this
function Lab(obj) {
var a = obj.getAttribute('name');
if (a != 'YtoD') {
document.getElementById("linechartxaxislabel").innerHTML = "Price Timeline" + "(Last" + a + ")";
} else {
document.getElementById("linechartxaxislabel").innerHTML = "Year to Date";
}
}
Firstly, the object you get in does not have a javascript attribute called name, as it's a DOM element. You need to access attributes using the DOM API (https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute)
Second, once you have the name it's a String so you need to compare it with the String YtoD and not an object reference.
Related
Below is my (not working) code. I'm trying to write a function that allows me to enter in any name into the console.log and then have that name attached to the message. Please see below for clarification:
function checkAge(name, age) {
name = {};
if (age >= 21) {
return ("Welcome," + {} + "!");
}
else return ("Go home," + {} + "!");
}
console.log(checkAge('Adrian', 22)); //Welcome,[object Object]!
Expected result should be 'Welcome, Adrian!' (and not Welcome, [object, Object]!). BUT I don't want to hard code names so I can't just write
name === 'Adrian' since it needs to work for any name. Any advice? Thank you! :)
Remove the name = {}; you are reassigning parameter name and not passing the parameter to the return of string.
function checkAge(name, age) {
if (age >= 21) {
return ("Welcome," + name + "!");
}
else return ("Go home," + name + "!");
}
console.log(checkAge('Adrian', 22));
output >> Welcome,Adrian!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is a new edit to my question, hopefully it will meet the criteria and be considered eligible.
First, I managed to solve the problem. I will now describe the situation and what I think the solution that solve the problem.
My code gets a string (a call number) as an input, re-formats it, parse it to float, and return the call number location within a given set of ranges.
The code is composed of two functions: 1. formatCallNumber(callNum) which does the text manipulation to the input. 2. SortCallNum(callNumInput) - responsible on the sorting to ranges part.
The problem was in passing values of call number ranges from the sorting function (no.2) to the formatting function (no.1). Although I parsed those values as strings in the sorting function, the .replace function produced an error. The solution that I (think) worked, was to parse the values to strings in the formatting function.
The code of the two functions below is updated and seems to be working as expected:
function 1 - formatting function:
function formatCallNumber(callNum){
var formatedCallNum = String(callNum);
formatedCallNum = formatedCallNum.replace(/\D/g,''); // remove all but digits chars from the string (whitespace, dots, etc)
formatedCallNum = "0." + formatedCallNum; // add "0." to the callNumber string
formatedCallNum = parseFloat(formatedCallNum); // parse as float - so it could be compared with other decimals
return (formatedCallNum);
}
Function 2 - the sorting function:
function SortCallNum(callNumInput){
// data [test only]
var shelves = {
"S1" : {"callStart":"100","callEnd": "223.456", "id": 1},
"S2" : {"callStart":"223.457","callEnd": "334", "id": 2},
"S3" : {"callStart":"335","callEnd": "535", "id": 3},
"S4" : {"callStart":"536","callEnd": "638", "id": 4},
"S5" : {"callStart":"639","callEnd": "847", "id": 5}
};
var matchId = "";
document.getElementById("somthing").innerHTML += "you typed the number: " + callNumInput; // output of callNumInput (as inserted by user)
formatedCallNum = formatCallNumber(callNumInput);
// traverse into shelves object : iteration of objects (key = s1-s5)
for (var key in shelves) {
if (shelves.hasOwnProperty(key)) {
matchId = shelves[key].id;
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallEnd is: " + " -- " + shelves[key].callEnd); // display values of object shelves.key.callend
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallStart is: " + " -- " + shelves[key].callStart); // display values of object shelves.key.callend
var formatedCallRangeStart = formatCallNumber(shelves[key].callStart);
var formatedCallRangeEnd = formatCallNumber(shelves[key].callEnd);
console.log(formatedCallRangeStart);
console.log(formatedCallRangeEnd);
if ((formatedCallNum <= 0) || (formatedCallNum > 1)){alert('call number not in proper range'); break;}
if ((formatedCallRangeStart <= formatedCallNum)&&(formatedCallRangeEnd >= formatedCallNum)){break;}
}
}
Thanks for all the help.
As I can see, everythign should work as expected. It's important to pass a string into SortCallNum, and not a number.
function SortCallNum(callNumInput){
// data [test only]
var shelves = {
"S1" : {"callStart":100,"callEnd": "223", "id": 1},
"S2" : {"callStart":224,"callEnd": "334", "id": 2},
"S3" : {"callStart":335,"callEnd": "535", "id": 3},
"S4" : {"callStart":536,"callEnd": "638", "id": 4},
"S5" : {"callStart":639,"callEnd": "847", "id": 5}
};
var matchId = "";
document.getElementById("somthing").innerHTML += "you typed the number: " + callNumInput; // output of callNumInput (as inserted by user)
formatedCallNum = formatCallNumber(callNumInput);
// traverse into shelves object : iteration of objects (key = s1-s5)
for (var key in shelves) {
if (shelves.hasOwnProperty(key)) {
matchId = shelves[key].id;
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallEnd is: " + " -- " + shelves[key].callEnd); // display values of object shelves.key.callend
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallStart is: " + " -- " + shelves[key].callStart); // display values of object shelves.key.callend
var formatedCallRangeStart = String(shelves[key].callStart);
formatedCallRangeStart = formatCallNumber(formatedCallRangeStart);
var formatedCallRangeEnd = String(shelves[key].callEnd);
formatedCallRangeEnd = formatCallNumber(formatedCallRangeEnd);
matchId = shelves[key].id;
if ((formatedCallRangeStart <= formatedCallNum)&&(formatedCallRangeEnd >= formatedCallNum)){
break;
}
}
}
alert (matchId);
}
function formatCallNumber(callNum){
// callNum = prompt('enter a call number: ');
formattedCallNum = callNum.replace(/\D/g,''); // remove all but digits chars from the string (whitespace, dots, etc)
formattedCallNum = "0." + formattedCallNum; // add "0." to the callNumber string
formattedCallNum = parseFloat(formattedCallNum); // parse as float - so it could be compared with other decimals
return (formattedCallNum);
}
SortCallNum('1337')
<div id="somthing"></div>
So, this would work SortCallNum('1337'), this not SortCallNum(1337)...
Another possible cause is that you trust the return-value from prompt blindly.
<button type="button" onclick="var callNumInput = prompt('enter a call number: '); SortCallNum(callNumInput);"> SortCallNum(test)</button>
When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns null.
https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Example
A bit of sanitization should help:
if (callNumInput == null) {
throw new Error('You have to insert a number between 0 and 999.')
}
the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.
Okay so i have started learning javascript from the book Beginning Javascript 5th ed, just confused by a js script
function getCookieValue(name) {
var value = document.cookie;
var cookieStartsAt = value.indexOf(" " + name + "=");
if (cookieStartsAt == -1) {
cookieStartsAt = value.indexOf(name + "=");
}
if (cookieStartsAt == -1) {
value = null;
} else {
cookieStartsAt = value.indexOf("=", cookieStartsAt) + 1;
var cookieEndsAt = value.indexOf(";", cookieStartsAt);
if (cookieEndsAt == -1) {
cookieEndsAt = value.length;
}
value = unescape(value.substring(cookieStartsAt,
cookieEndsAt));
}
return value;}
My question is how does the indexOf operator works here( i know how it works and used it previously) ??
The above program is defined below by the book which goes as :
The first task of the function is to get the document.cookie string and store it in the value variable
var value = document.cookie;
Next, you need to find out where the cookie with the name passed as a parameter to the function
is within the
value string. You use the inde x Of() method of the String object to find this
information, as shown in the following line:
var cookieStartsAt = value.indexOf(" " + name + "=");
The method will return either the character position where the individual cookie is found or ‐1 if no
such name, and therefore no such cookie, exists. You search on
" " + name + "=" so that you don’inadvertently find cookie names or values containing the name that you require. For example, if you
have
xFoo, Foo, and yFoo as cookie names, a search for Foo without a space in front would match
xFoo first, which is not what you want!
What the just just happened here?? How did they achieve the location of the name using indexOf() ?? please explain ? I couldn't understand the xfoo,foo,yfoo example ?? Looking for a simpler example.
document.cookie contains a string like cookiename=cookievalue
indexOf is getting the position of the begining of the value part of the cookie
var cookieStartsAt = value.indexOf("cookiename=");
That allows you to use that number to get the value portion of the string with substring()
I want to get the string value between ";L0|" and ";GTSet" from the following type of strings.
var test = "GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
var test2 = "GP0|#15a06b93-f7aa-4dda-b0d6-7bf2d2905f27;L0|#015a06b93-f7aa-4dda-b0d6-7bf2d2905f27|Special Event;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
Here is what i have done already.
var str = test2.match(";L0|" + "(.*?)" + ";GTSet");
alert(str[1]);
and this returns a string from the very beginning till the ";GTSet"
Jsfiddle link here
I guess you are getting this value from SharePoint Search results, right? If so, according to Automatically created managed properties in SharePoint Server 2013:
Data format for Managed Metadata.
To query for items tagged with a Managed Metadata field, you have to
use the Unique Identifier for each label. You can find the Unique
Identifier for each term in a term set in the Term Store Management
Tool, on the GENERAL tab. In addition, the data format that is used in
the query has to specify from which level in the term set the query
should apply. This specification is set by adding one of the following
prefixes to the Unique Identifier:
To query for all items that are tagged with a term: GP0|#
To query for all items that are tagged with a child of term: GPP|#
To query for all items that are tagged with a term from a term set: GTSet|#
Based on this information the following example demonstrates how to parse search result value for managed metadata:
function parseTaxonomySearchResultValue(val){
var taxValue = {TermSetGuids: [], TermValues: []};
var parts = val.split(';');
parts.forEach(function(part){
if (part.startsWith("GP0|#")) //term?
{
var termGuid = part.replace("GP0|#", "");
taxValue.TermValues.push({ TermGuid: termGuid});
}
else if (part.startsWith("GTSet|#")) //term set?
{
taxValue.TermSetGuids.push(part.replace("GTSet|#", ""));
}
else if (part.startsWith("L0|#")) //Term with label?
{
var termParts = part.replace("L0|#0", "").split('|');
var termGuid = termParts[0];
var termLabel = termParts[1];
var result = taxValue.TermValues.filter(function(tv){
return tv.TermGuid == termGuid;
});
if (result.length == 0)
taxValue.TermValues.push({TermGuid : termGuid, Label : termLabel});
else
result[0].Label = termLabel;
}
});
return taxValue;
}
//Usage
var taxValue = 'GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc';
var taxValue = parseTaxonomySearchResultValue(taxValue);
document.getElementById('output').innerHTML = "Term info:<br/>" + "Guid= " + taxValue.TermValues[0].TermGuid + "<br/> Label= " + taxValue.TermValues[0].Label;
<div id='output'/>