I am coding a quiz and need to have it display a certain answer depending on the score.
I had this working when I just had the score being displayed, but now that I have added in the if else, it has stopped working and I am getting an unterminated string constant
$total_score = $first_question + $second_question + $third_question + $fourth_question + $fifth_question + $sixth_question + $seventh_question + $eighth_question + $ninth_question + $tenth_question + $eleventh_question + $twelfth_question + $thirteenth_question + $fourteenth_question + $fifthteenth_question + $sixteenth_question ;
});
$("#btn").click(function() {
$('#reveal').html("<h3><strong>Total score</strong> " + $total_score +"</h3>");
if ($total_score >= 13) {
$('#answer').html("<h3><strong>13-16: Answer</strong></h3>");
} else if ($total_score >=9 && $total_score <= 12) {
$('#answer').html("<h3><strong>9-12: answer</strong></h3>");
} else if ($total_score >=5 && $total_score <= 8) {
$('#answer').html("<h3><strong>5-8: answer</strong></h3>");
} else {
$('#answer').html("<h3><strong> everything else</strong></h3>");
}
});
In addition to the line breaks as #Spork noted, you need to remove the extraneous "})" after the $total_score calculation:
$total_score = $first_question + $second_question + $third_question + $fourth_question + $fifth_question + $sixth_question + $seventh_question + $eighth_question + $ninth_question + $tenth_question + $eleventh_question + $twelfth_question + $thirteenth_question + $fourteenth_question + $fifthteenth_question + $sixteenth_question ;
/* must remove the following:
});
*/
$("#btn").click(function() {
$('#reveal').html("<h3><strong>Total score</strong> " + $total_score +"</h3>");
if ($total_score >= 13) {
$('#answer').html("<h3><strong>13-16: Answer </strong></h3>");
} else if ($total_score >=9 && $total_score <= 12) {
$('#answer').html("<h3><strong>9-12: answer </strong></h3>");
} else if ($total_score >=5 && $total_score <= 8) {
$('#answer').html("<h3><strong>5-8: answer </strong></h3>");
} else {
$('#answer').html("<h3><strong> everything else</strong></h3>");
}
});
Javascript treats line ends roughly as semicolons (;), so you cannot have multi-line strings as you have in your script. Remove them, and it'll be okay.
Related
Very new to JavaScript, the first programming language I learned was Java. I am trying to make a simple website that displays the shortest distance between an infinite number of points using prompt boxes and a 2D array.
This code works as expected, however when one of the points has a negative number in it, nothing ever displays for an answer, throwing the error:
Uncaught TypeError: Cannot read property '0' of undefined
at run (index.html:54)
at HTMLButtonElement.onclick (index.html:63)
Google Chrome highlights the error at this line:
toRun = "Shortest distance is " + min + " with these points: (" + finalPoints[0][0] + ", " + finalPoints[1][0] + ") and (" + finalPoints[0][1] + ", " + finalPoints[1][1] + ").";
How can I get this program to work with negative numbers as well?
function run() {
var x, y;
var finalPoints = [];
var min = 0;
var toRun;
var temp;
var list = []; //using 2d array to store points
while (true) {
x = prompt("Enter an X-Value: ");
if (x == null || x == "") {
break;
}
y = prompt("Enter a Y-Value: ");
if (y == null || y == "") {
break;
}
list.push([x, y]);
}
if (list.length < 2) {
toRun = "Sorry, you didn't enter enough points for this program to run correctly. Please try again.";
} else if (list.length == 2) {
toRun = "Distance between points (" + list[0][0] + ", " + list[0][1] + ") and (" + list[1][0] + ", " + list[1][1] + ") is " + Math.sqrt(Math.pow((list[0][0] - list[1][0]), 2) + Math.pow((list[0][1] - list[1][1]), 2));
} else {
min = Math.sqrt(Math.pow((list[0][0] - list[1][0]), 2) + Math.pow((list[0][1] - list[1][1]), 2));
for (var i = 0; i < list.length; i++) {
for (var j = 0; j < list.length; j++) {
temp = Math.sqrt(Math.pow((list[i][0] - list[j][0]), 2) + Math.pow((list[i][1] - list[j][1]), 2));
if (temp < min && temp != 0) {
min = temp;
finalPoints.push([list[i][0], list[j][0]]);
finalPoints.push([list[i][1], list[j][1]]);
}
}
}
toRun = "Shortest distance is " + min + " with these points: (" + finalPoints[0][0] + ", " + finalPoints[1][0] + ") and (" + finalPoints[0][1] + ", " + finalPoints[1][1] + ").";
}
document.getElementById("output").innerHTML = toRun;
}
body {
background-color: #0d0d0d;
}
p,
button,
h3 {
color: #FFFFFF;
background-color: #0d0d0d;
}
button {
border: 1px solid #FFFFFF;
}
<h3>Continue entering points. When done, click cancel or don't enter anything.</h3>
<br>
<button onclick="run()" style="size:40%">Click me to start!</button>
<p id=output>(Output will display here).</p>
Javascript we had for Unified interface of Dynamics 365 to format phone numbers was working perfectly until the latest update, now it only works in custom interface and has stopped working in UI, anybody has any idea how this can be fixed?
var XXX = window.XXX || {};
(function() {
// Code to run in the form OnLoad event
this.formOnLoad = function(executionContext) {
var formContext = executionContext.getFormContext();
// display the form level notification as an INFO
formContext.ui.setFormNotification(message, "INFO", myUniqueId);
// Wait for 5 seconds before clearing the notification
window.setTimeout(function() {
formContext.ui.clearFormNotification(myUniqueId);
}, 5000);
}
// Code to run in the attribute OnChange event
this.mobilePhoneFormatting = function(executionContext) {
var formContext = executionContext.getFormContext();
var mobilePhone = formContext.getAttribute("mobilephone").getValue();
var formatPhone = "";
try {
if (mobilePhone != null) {
var phoneNumbers = mobilePhone.replace(/\D/g, '');
if (phoneNumbers.length == 10) { //10 digit case. Output adds +1 and proper format
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10));
} else if (phoneNumbers.length == 11) { //11 digit case. Output proper format
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11));
} else if (phoneNumbers.length == 14) { //14 digit case. Without Country code and with extension
formatPhone = ("+1 (" + phoneNumbers.substring(0, 3) + ") " + phoneNumbers.substring(3, 6) + "-" + phoneNumbers.substring(6, 10) + " x" + phoneNumbers.substring(10, 14));
} else if (phoneNumbers.length == 15) { //15 digit case. With Country code and extension
formatPhone = ("+" + phoneNumbers.substring(0, 1) + " (" + phoneNumbers.substring(1, 4) + ") " + phoneNumbers.substring(4, 7) + "-" + phoneNumbers.substring(7, 11) + " x" + phoneNumbers.substring(11, 15));
} else if (phoneNumbers.length == 4) { //4 digit case. Extension Only
formatPhone = ("x" + phoneNumbers.substring(0, 4));
} else {
formatPhone = mobilePhone;
}
formContext.getAttribute("mobilephone").setValue(formatPhone);
formContext.data.entity.save();
}
} catch (err) {
txt = "There was an error formatting the Phone Number.\n\n";
txt += "Error description: " + err.message + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
// var
var differentBillsInUSD;
// start of bills
differentBillsInUSD = {
firstBill: parseInt(124),
secondBill: parseInt(48),
thirdBill: parseInt(268),
fourthBill: parseInt(180),
fifthBill: parseInt(42),
}
// console to check if everything is alright
console.log(differentBillsInUSD);
console.log("Checking if bill is alright ^");
function calcBill(numberBill) {
if (numberBill < 50) {
return(numberBill + " tip is: " (numberBill*0.20));
} else if (numberBill >= 50 && numberBill <= 200) {
return(numberBill + " tip + total is: " (numberBill*0.15));
} else if (numberBill > 200) {
return(numberBill + " tip + total is: " (numberBill*0.20));
}
}
function calcBillTotal(numberBill) {
if (numberBill < 50) {
return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
} else if (numberBill >= 50 && numberBill <= 200) {
return(numberBill + " tip + total is: " ((numberBill*0.15)+numberBill));
} else if (numberBill > 200) {
return(numberBill + " tip + total is: " ((numberBill*0.20)+numberBill));
}
}
// first bill
console.log(calcBill(differentBillsInUSD.firstBill));
console.log(calcBillTotal(differentBillsInUSD.firstBill));
// second bill
cosnole.log(calcBill(differentBillsInUSD.secondBill));
cosnole.log(calcBillTotal(differentBillsInUSD.secondBill));
ERROR CODE
script.js:21 Uncaught TypeError: " tip + total is: " is not a function
at calcBill (script.js:21)
at script.js:37
It won't work because I am doing to a coding challenge.
It also seems that I am new to javascript.
I tried to do my research, it was very difucult to find.
I am in the middle of code but can not fix.
return(numberBill + " tip is: " + (numberBill*0.20));
you just miss to place a plus sign inside...
return(numberBill + " tip + total is: " (numberBill*0.15));
In JS when you place () after anything it tries to execute it as a function. as you missed the "+" just before "(numberBill*0.15)", so its trying to execute " tip + total is: " as a function. You just need to add a "+"
when you are concatenating a string with a variable , you need to use "+" sign in javascript. Here if you noticed in each if ,else if and else statement you are missing "+" sign.
if (numberBill < 50) {
return(numberBill + " tip is: " + (numberBill*0.20));
First of all, I am not very good at javascript. Well what I am trying to do is create a sort of wheel spinning program where, on a button click, you will either get extra spins, nothing, or it will send me an email with a secret code and I will reply in the email how much they will win. Hopefully you understand what I mean and know why its not working.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, user-scalable=no">
<title>Spin the Wheel!</title>
</head>
<body>
<button name="generate" type="button" onClick="gennum()">Spin!</button>
<script>
function gennum() {
var result=Math.floor(Math.random()*101)
check()
}
function check() {
if (result > 0 && result < 11) {
alert("You win 1 free spin! Spin again!")
}
else if (result > 10 && result < 16) {
alert("You win 2 free spins! Spin again twice!")
}
else if (result > 15 && result < 26) {
alert("Sorry, you won nothing. Please try again tommorow.")
}
else if (result > 25 && result < 36) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('7L6XPaY8').value)
;
window.location.href = link;
}
else if (result > 35 && result < 45) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('NmE6B5uF').value)
;
window.location.href = link;
}
else if (result > 44 && result < 52) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('ZpLb9TRC').value)
;
window.location.href = link;
}
else if (result > 51 && result < 59) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('JQa6fGHH').value)
;
window.location.href = link;
}
else if (result > 58 && result < 64) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('rKjPGXak').value)
;
window.location.href = link;
}
else if (result > 63 && result < 69) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('5QQyCJaD').value)
;
window.location.href = link;
}
else if (result > 68 && result < 71) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('474zbnkE').value)
;
window.location.href = link;
}
else if (result > 70 && result < 74) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('QUjY2NSN').value)
;
window.location.href = link;
}
else if (result > 73 && result < 76) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('FNVYSHu5').value)
;
window.location.href = link;
}
else if (result > 75 && result < 100) {
alert("Sorry, you won nothing. Please try again tommorow.")
}
else if (result = 100) {
var link = "mailto:name#example.com"
+ "&subject=" + escape("Spinner")
+ "&body=" + escape(document.getElementById('uZ63V4me').value)
;
window.location.href = link;
}
}
</script>
</body>
</html>
That is all of the code. If you know why it is not working, reply please.
You have to pass result to the function otherwise it's out of scope:
function gennum() {
var result=Math.floor(Math.random()*101)
check(result)
}
function check(result) {
...
}
In your case result is defined inside gennum and check has no access to it.
result is not declared as a global variable, so it is empty when it reaches check().
Pass it as a parameter on check()
function gennum() {
var result=Math.floor(Math.random()*101)
check(result);
}
function check(param) {
// and so on and so forth
}
you can declare result variable outside of your function to publically access it through all methods
var result;
function gennum() {
result=Math.floor(Math.random()*101);
check();
}
function check() {
//do something here ...
}
or
you should to declare a parameter for check function and pass value to it.
function gennum() {
var result=Math.floor(Math.random()*101);
check(result);
}
function check(result) {
//do something here ...
}
I'm trying to make 10 digits look like a US telephone number (i.e.(###) ###-####). My code does accomplish this first goal, but it also does something I can't quite figure out. When typing in the digits, the characters "()" show up before typing any other digits. I want the open parenthesis to appear first and the closing parathesis to appear after entering the third digit. Please don't give me a new solution; try to pin point the issue I'm describing.
<script type="text/javascript">
$('.drumbi-caller-number').live('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
} else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,9);
var string = ("(" + first3 + ")" + next3 + "-" + next4);
$(this).val(string);
}
});
</script>
Here's a jsFiddle that displays this behavior: http://jsfiddle.net/bigthyme/j6kHn/3/
replace keydown with keyup, on keydown the value of the input element isn't updated
also set your string conditionally, only if long enough:
var string = string.length > 2 ? ("(" + first3 + ")" + next3 + "-" + next4) : first3;
here is the code: http://jsfiddle.net/j6kHn/10
btw: you should also replace .live(...) with .on(...) as .live() is deprecated..
You need to check the length of first3 before appending the paren:
var string = ("(" + first3 + ((first3.length>=3)?")":"") + next3 + "-" + next4);
And although not in your question, you can do the same for the hyphen:
var string = ("(" + first3 +
// only append the ) if the you have 3+ chars
((first3.length>=3)?")":"") +
next3 +
// only append the - if the you have 6+ chars
(((first3+next3).length>=6)?"-":"") +
next4);
You should also use .on() instead of live();
See it all working in this jsFiddle
Go with
$('.foo').on('keyup', function (event) {
$(this).val($(this).val().replace(/\D/g, "").replace(/(\d{0,3})(\d{0,3})(\d{0,4}).*/, "($1) $2-$3"));
});
Test this code here.
Try using this code, it should fix all of your issues:
Demo: http://jsfiddle.net/bN6Rh/3/
jQuery:
$('.foo').on('keyup', function(event) {
if (event.keyCode == (8 || 37 || 39)) { }
else {
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0, 3);
var next3 = " " + string.substring(3, 6);
var next4 = string.substring(6, 10);
if (string.length < 3) { // Less than 3
var string = "(" + first3;
}
else if (string.length > 2 && string.length < 7) { // More than 2 and less than 7
var string = "(" + first3 + ")" + next3;
}
else { // Anything else
var string = "(" + first3 + ")" + next3 + "-" + next4;
}
$(this).val(string);
}
});
The problem was that you weren't checking the number of characters so as soon as anything was entered it put in ()-, the above code also adds the space you mentioned wanting.
The code could of course be more compressed:
$('.foo').on('keyup', function(e) {
if (e.keyCode == (8 || 37 || 39));
else {
var str = this.value.replace(/[^0-9]/g, "");
var f3 = str.substring(0, 3),
n3 = " " + str.substring(3, 6),
n4 = str.substring(6, 10);
if (str.length<3) str = "(" + f3;
else if (str.length>2&&str.length<7) str="("+f3+")"+n3;
else str="("+f3+")"+n3+"-"+n4;
this.value = str;
}
});