Suceeded in randomizing a quote but now the values name and quote don't match, is there a way to make json.name and json.quote share the same random value? so Einstein's quote isn't matched with the name Nightingale.
let url =;
$.getJSON( url, function( json ) {
let rand = function getRandom() {
return Math.floor(Math.random() * 4) + 1 ;
}
//console.log(rand());
document.write(" "" + json[rand()].quote +""" + " by "
+json[rand()].name );
});
document.write(" "" + json[rand()].quote +""" + " by "
+json[rand()].name );
everytime you use rand(), it will generate a different number, so json[rand()].quote and json[rand()].name will be different because you are using different keys, so save rand() in a variable first and then use it, like:
var randNumber = rand();
document.write(" "" + json[randNumber].quote +""" + " by " +json[randNumber].name );
Related
Good morning folks. I just started to learn JS and got a task in which I am stuck. I need to change number format to have 2 decimal places and it should also start with pound sign.
function formatCurrency() {
var formated = formated.toFixed(2);
return formated;
}
function calculateSalesTax(price: number) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
When I tried to shorten numbers it throws me an error.Could you please point me in correct direction, as it looks like a very simple task.
Try like this:
function formatCurrency(price) {
var formated = price.toFixed(2);
return formated;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
The formatCurrency function needs to accept an argument (the price) passed into it and use that in the formatting.
The calculateSalesTax function shouldn't have the type definition added to the argument (this is fine in TypeScript).
Here is your correct code:
function formatCurrency(price) {
return `\u00A3 ${price.toFixed(2)}`;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
You were not declaring an argument for formatCurrency. \u00A3 is the code for the pound sign, as putting £ will result in a bad behaviour in js. The backticks (``) allows you to use "literal", go search for it, it is a useful tool in javascript. Also, you attempted to declare a return type for calculateSalexTaxPrice, which you can not since typing is possibile in TypeScript only
I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}
I am working on VS2103 Cordova App. I have created list of items. I want to pass data to another page when i press on item. I've created this list by jQuery.
Here is my code :
for (var i = 0; i < data.length; i++) {
if ((Provider == "Doctors")) {
$("#list").append('<li class="list-message" ><a class="w-clearfix w-inline-block" href="javascript:ProviderDetails(' + data[i].DoctorName + ',' + data[i].DoctorAddress + ',' + data[i].DoctorPhone + ',' + data[i].DoctorPhone2 + ',' + data[i].DoctorPhone3 + ',' + data[i].DocLat + ',' + data[i].DocLong + ',' + data[i].DoctorNotes + ',' + data[i].Category + ');" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/Doctors.png"></div></div><div class="column-right"><div class="message-title">' + data[i].DoctorName + '</div><div class="message-text">' + data[i].DoctorAddress + '</div></div></a></li>');
}
}
And here is my function :
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category) {
localStorage.setItem("Name", Name);
localStorage.setItem("Address", Address);
localStorage.setItem("Tel", Tel);
localStorage.setItem("Phone2", Phone2);
localStorage.setItem("Phone3", Phone3);
localStorage.setItem("Lat", Lat);
localStorage.setItem("Lang", Lang);
localStorage.setItem("Notes", Notes);
localStorage.setItem("Category", Category);
window.location.href = "../Details.html";
}
It doesn't do any thing when i press any items . Any help ?
Pay attention on how you build the string:
href="javascript:ProviderDetails(' + data[i].DoctorName + ',' ......
you need to add the string delimiters:
href="javascript:ProviderDetails(\'' + "data[i].DoctorName" + '\',\'' .....
Your function is declared as:
function ProviderDetails(Name, Address, Tel, Phone2, Phone3, Lat, Lang, Notes, Category)
{
....
}
Now, because your function expects strings as input you can call your function as:
ProviderDetails('string1', 'string2', .....)
Your javascript loop instead produces:
ProviderDetails(string1, string2, .....)
For javascript now the parameters are considered as variables, i.e., string1 is no more a string but a value contained in the variable string1.
But because you do not have such a variable your function call does not work.
So, the delimiters are important to instruct js to understand the beginning and end of a string.
As a delimiter you can you the symbols: ' or ".
But you need to escape the delimiter itself if you want to use it inside the strings:
var a = 'this isn't a string'; // wrong because the inner delimiter is not escaped.
var a = 'this isn\'t a string'; // OK because the inner delimiter is escaped
Of course if you use inside the string the other delimiter you do not need to escape it.
var a = "this isn't a string"; // this is OK
I have some JavaScript, when a user enters in 10 digits in the phone field,it checks whether the country field has been populated so that it can assign a country code to it. See code below.
if (Country != null) {
var CountryName = Country[0].name;
var CountryId = Country[0].id;
var CountryType = Country[0].entityType;
if (CountryName == "United States of America") {
PhoneTemp = "+1 " + "(" + PhoneTemp.substr(0, 3) + ") " + PhoneTemp.substr(3, 3) + " - " + PhoneTemp.substr(6, 4);
} else if (CountryName == "India") {
PhoneTemp = "+91 " + PhoneTemp.substr(0, 4) + " " + PhoneTemp.substr(4, 6);
}
}
If i do it this way ill end up with a 100+ else if, is there a nicer way of doing it?
You can use switch or you can use Jquery $.inArray(val, array)
http://www.w3schools.com/js/js_switch.asp
http://api.jquery.com/jquery.inarray/
I would go for a map to abstract the country logic
var countryMap = {
'USA': usaLogic,
'FR': frLogic
};
function usaLogic(number) {
return "+1 " + "(" + number.substr(0, 3) + ") " + number.substr(3, 3) + " - " + number.substr(6, 4);
}
function frLogic(number) {
return ".....";
}
Then you can reduce your if statement to the following:
if (countryMap[CountryName]) {
PhoneTemp = countryMap[CountryName](PhoneTemp)
}
You can make an array or structure with countries and the phone prefix.
var Countries = ['India', 'France', 'Spain'];
var Prefixes = [91, 32, 34];
And with it you can save all if-else statements just calling the correct key in array.
Create a dictionary of country converters.
PhoneCountryConverters["India"] = function(PhoneTemp) { return "+91 " + PhoneTemp.substr(0, 4) + " " + PhoneTemp.substr(4, 6);}
usage:
PhoneTemp = PhoneCountryConverters[Country[0].name](PhoneTemp);
PhoneCountryConverters will have an entry for each country, and you eliminate if statements altogether.
Hi brother you can use two arrays like this :
var CountriesPrefix = {'usa': '+1','India': '+2', 'morocco': '+212'};
var Countries = ['usa', 'India', 'morocco'];
var CountryName='usa';
if($.inArray(CountryName, countries)==0){ //The country is in array
var PhoneTemp = countries_prefix[CountryName];
}
Using associative array here will reduce the pain of indexs between arrays by using the keys (the keys here are the Countries names).
I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";