Declaration or statement expected in else statement - javascript

I'm fairly new to java script and I've encountered a problem while trying to make a else statement in visual studio 2017.
I've tried moving the curly brackets and the else around to see if maybe I've placed them into the wrong place and I've had no luck.
<script type="text/javascript">
var items = parseInt(prompt("enter number of items", ""));
var price = parseFloat(prompt("enter item price", ""));
var total = items * price
if (total >= 50); {
document.write("<h3>" + "cost... $" + total * .5 + "</h3>");
document.write("<h2>" + prompt("enter a name", "") + "</h2>");
}
else {
document.write("<h3>" + "cost... $" + total + "</h3>");
document.write("<h2>" + prompt("enter a name", "") + "</h2>");
}
</script>
Whenever I open it in a web page, nothing happens, But when i get rid of the else statement, the if statement would execute.

Delete the semicolon behind the if condition and then the code should work.

Related

How to check if number is up of multiplication table jquery/javascript

On my store, I want to offer a promotion for people who buy up to 1499, 2998, 4497, etc. (it is a multiplication of 1499);
do you recommend me use the conditional if? use switch? or what do you do in this case?
I ask you this be cause when they buy up to the values (1499,2998, etc) I need to show a div saying that the person won a promotion
I'm thinking do a multiplication of 1499 and check the total of the person is up to 1499,2998 etc, actually a make a multiplication table but I dunno how to check if is between a range
var i = 0;
document.write('<table border="1" cellspacing="0">');
for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");```
The table can be there just for display.
const num = 1499;
var i = 0;
document.write('<table border="1" cellspacing="0">');
for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");
To actually calculate the amount won from what the user has bought, divide the amount by 1499 and then call Math.floor on it:
const amountWon = input => Math.floor(input / 1499);
console.log(
amountWon(1498),
amountWon(1499),
amountWon(1500),
amountWon(2997),
amountWon(2998),
);
But make sure to do the calculation on the server-side as well, since none of the code you run on the client side can be trustworthy.

Javascript: Having issues calling function(Cannot read property 'value' of null)

So i've been trying to debug this for a few hours and I'm completely stuck. When I go on the webpage I get this error in the console:
(Cannot read property 'value' of null at totalCost (assn1.html:18) at assn1.html:26 totalCost # assn1.html:18
(anonymous) # assn1.html:26.
My program is all finished I just can't get it to call the function and print the name, number of cups and the total cost at the end.
Heres my code:
<html>
<head>
<title>Tea Shoppe</title>
</head>
<body>
<section>
<h1> Welcome to the Tea Shoppe!</h1>
<p>
<img src = "http://nobacks.com/wp-content/uploads/2014/11/Tea-Cup-5-500x476.png" />
</p>
</section>
<script>
function totalCost()
{
var cups = parseInt(document.getElementById("cups").value);
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
totalCost(cups);
document.write("Ok" + name + ", you ordered" + cups + " of tea" + "your total price is" + totalCost);
</script>
</body>
</html>
document.getElementById("cups")
You have no element with that ID in your document.
function totalCost(cups)
{
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
document.write("Ok " + name + ", you ordered" + cups + " of tea" + " your total price is " + totalCost(cups));
Here's a working version of your code, what i did here is adding teh totalcost function parameter since you pass it when you call the function and got rid of the cups variable inside your function because it has nothing to do there and was causing an error also + and changed the place where you function should be called from since it returns the totalcups value it must be put inside the document.write function to return the total in it's perfect place.
that's all and i hope this fixed your problem.
herre's a working fiddle https://jsfiddle.net/bgn4x7ej/

JS/jQuery Recalculate object constructor values from button onclick->prompt

I am having trouble dynamically updating values in a jQuery-generated table.
I inserted a button next to values that the contents of adjacent <td> are calculated from, with the intent that the .click(function(){ prompt("...","...")} would not only update the value of interest (hours, avgCustomers, avgPurchase), but also recalculate the dependent <td>.
The contents of the table are calculated on $(document).ready from an object constructor, using arrays for the input values (see Shops.js # http://github.com/jacobshillman/Week2A2.git, and/or below). In the git, 'index.html' is the page of interest.
A click event updates the value displayed, but I haven't been able to figure out how to get the rest of the table to recalculate based on the new value.
//Donut Shop Constructor
function Shop (loc, hours, minCust, maxCust, avgDonCust, avgCust, donHr, donDay) {
this.loc = loc;
this.hours = hours;
console.log(this.loc + ", Hours: " + this.hours);
this.minCust = minCust;
this.maxCust = maxCust;
this.avgDonCust = avgDonCust;
//Random sample of average customers per hour:
this.avgCust = getCustpHr(this.hours, this.minCust, this.maxCust);
console.log(this.loc + ", Customers per hour: " + this.avgCust);
//Donuts to bake per hour:
this.donHr = getDon(this.avgCust, this.avgDonCust)
console.log(this.loc + ", Donuts to bake per hour: " + this.donHr);
//Donuts to bake per day:
this.donDay = getSum (this.donHr)
console.log(this.loc + ", Donuts to bake per day: " + this.donDay);
};
//Donut Shops declaration:
var Shops = [5];
Shops[0] = new Shop("Downtown", 8, 8, 43, 4.5);
Shops[1] = new Shop("Capitol Hill", 24, 4, 37, 2);
Shops[2] = new Shop("South Lake Union", 10, 9, 23, 6.33);
Shops[3] = new Shop("Wedgewood", 7, 2, 28, 1.25);
Shops[4] = new Shop("Ballard", 10, 8, 58, 3.75);
//Populate index.html with Donut shops stats:
$(document).ready(function(){
$.each(Shops, function(){
$row = $('<tr></tr>');
$('#shopGrid tbody').append($row);
$row.append($('<td><ul>' + this.loc + '<li>Hours Open: ' +
'<span id="Hour">' + this.hours + '</span>'
+ '<input type="button" class="edit" value="EDIT">' + '</li>'
+ '<li>Average Purchase:' +
'<span id="Purch">' + this.avgDonCust + '</span>'
+ '<input type="button" class="edit" value="EDIT">' + '</li>'
+ '<li>Store Traffic:' +
'<span id="Traffic">' + this.minCust + '-' + this.maxCust + '</span>'
+ '<input type="button" class="edit" value="EDIT">' + '</li></ul>'))
//.slice() is inserted to control formatting:
$row.append($('<td>' + this.avgCust.slice(0,8) + '<br>'
+ this.avgCust.slice(8,16) + '<br>'
+ this.avgCust.slice(16) +'</td>'));
$row.append($('<td>' + this.donHr.slice(0,8) + '<br>'
+ this.donHr.slice(8,16) + '<br>'
+ this.donHr.slice(16) + '</td>'));
$row.append($('<td>' + this.donDay + '</td>'));
});
//Shop stats EDIT buttons:
//If else for EDIT button fX:
$(".edit").click(function(){
var test = $('#Hour').text();
console.log(test);
var newHours = prompt("Enter new number between 0 and 24", "New Hours");
if (newHours <= 24) {
$('#Hour').text(newHours);
test = newHours
}else{
alert('Must be a number between 0 to 24.')
}
console.log(test);
console.log(document.getElementById('Hour'));
});
/*
$(".edit").click(function(){
if ($('#Hour')) {
var newHours = prompt("Enter new number between 0 and 24", "New Hours");
if (newHours <= 24) {
$('#Hour').value(newHours);
}else{
alert('Must be a number between 0 to 24.')
}
}else if ($('#Purch')) {
var newVal = prompt("Enter new value:", "Enter number");
$(this.avgDonCust).val(newVal);
}else if ($('#Traffic')) {
var newVal = prompt("Enter first value:", "Enter number");
$(this.minCust).value(newVal)
var val2 = prompt("Enter second value", "Enter number");
$(this.maxCust).value(Val2);
};
});
*/
/*
//Switch for EDIT buttons fX:
$(".edit").click(function (){
switch (n){
case $('#Hour')
var newHours = prompt("Enter new number between 0 and 24", "New Hours");
if newHours <= 24 {
$(this.hours).val(newHours);
}else{
alert('Must be a number between 0 to 24.');
break;
case $('Purch'):
var newVal = prompt("Enter new value:", "Enter number");
$(this.avgDonCust).val(newVal);
case $('#Traffic'):
var newVal = prompt("Enter first value:", "Enter number");
$(this.minCust).val(newVal);
function() {
var val2 = prompt("Enter second value", "Enter number");
$(this.maxCust).val(Val2);
};
break;
}
*/
});
The code commented out and in console.log() are my attempts at troubleshooting and getting the table to recalculate.
Best I can figure is that I need to update the corresponding value in the 2-D array Shops - Shops[this][[1] to update the "Hours Open:" of any given shop, then triggering the calculations again, without reloading the page.
I tried in an earlier (failed) attempt to use objects instead of arrays, but descended into defining jQuery var=s hell because I had to hand-jam all the object names into html and jQuery. This attempt can be seen in the 'Legacy' directory in the .git, above.
I've seen updateTo() and recompute() advice on Stack Overflow, but I'm not sure whether/how I'd be able to integrate them.
Any input is greatly appreciated! I'm not opposed to scrapping things and starting from scratch: this is a learning exercise.
I'm not able to make a working example as I'm pressed for time, but I can give you a few suggestions. These suggestions are only for if you're not coding a reusable library.
I'd create properties (functions) that recompute other properties and/or the html.
var _total = 0, _tax = 0, _grand = 0;
function totalChange() {
$('#prop1').val(_prop1);
tax(_total * .08)
_.debounce(_grand);
}
function total(val) {
if(val) {
_total = val;
totalChange();
}
return _total;
}
Then you can create a getter and setter for each of your properties that sets html or other properties.
I would actually recommend emberjs or angular or backbone as they provide the exact functionality you're looking for.
I was bored today and created a jsfiddle for you using ember. Let me know if you have an questions.

Leading zeros from PDF field to javascript variable

Hopefully this is the correct place to ask this question. I'm pretty much brand new to javascript, but seeing it's similarities to the other languages I write in, it's been pretty easy so far- until now.
I'm writing a script for a button that is clicked when a user is done filling out a grid. The script goes through the fields in the grid, grabs the information, and generates an email. It then sends out a mailto: command with the information that was generated, much easier than the user having to type the email themselves. The problem I'm having is that one of the criteria for a field is a Tax ID, which can sometimes start with a zero, and when I go to assign that field value to a variable, it drops the leading zero. How do I get javascript to keep this leading zero? I've tried declaring a variable with a " " at the beginning to try to force it to recognize the variable as a string, but that doesn't seem to work.
Here's my code:
if(this.getField("ProviderOne").value != "")
{
// This is the form return email. Its hardcoded
// so that the form is always returned to the same address
var cToAddr = "blank#blank.org";
// First, get the client CC email address
var cCCAddr = "blank#blank.com";
var pOneTaxID = new String(this.getField("ProviderOneTaxID").value); //tring to force string value
// Set the subject and body text for the email message
var ProviderOne = this.getField("ProviderOne").value + " NPI:" + this.getField("ProviderOneNPI").value + " Tax ID:" + pOneTaxID;
var ProviderTwo = this.getField("ProviderTwo").value + " NPI:" + this.getField("ProviderTwoNPI").value + " Tax ID:" + this.getField("ProviderTwoTaxID").value;
var ProviderThree = this.getField("ProviderThree").value + " NPI:" + this.getField("ProviderThreeNPI").value + " Tax ID:" + this.getField("ProviderThreeTaxID").value;
var ProviderFour = this.getField("ProviderFour").value + " NPI:" + this.getField("ProviderFourNPI").value + " Tax ID:" + this.getField("ProviderFourTaxID").value;
var ProviderFive = this.getField("ProviderFive").value + " NPI:" + this.getField("ProviderFiveNPI").value + " Tax ID:" + this.getField("ProviderFiveTaxID").value;
var cSubLine = this.getField("ProviderOne").value + " ERA setup for [BLANK]";
var cBody = "To [BLANK], \n \nPlease enroll the following providers to receive [BLANK] through [BLANK] under [BLANK]: \n \n";
if(this.getField("ProviderOne").value != "")
cBody += "1. " + ProviderOne + "\n";
if(this.getField("ProviderTwo").value != "")
cBody += "2. " + ProviderTwo + "\n";
if(this.getField("ProviderThree").value != "")
cBody += "3. " + ProviderThree + "\n";
if(this.getField("ProviderFour").value != "")
cBody += "4. " + ProviderFour + "\n";
if(this.getField("ProviderFive").value != "")
cBody += "4. " + ProviderFive + "\n";
cBody += "\n Thank you,\n" + this.getField("ProviderOne").value;
app.mailMsg({bUI: true, cTo: cToAddr, cCc: cCCAddr, cBCc: "", cSubject: cSubLine, cMsg: cBody});
}
else
{
app.alert("Please enter at least one payer into the grid above.", 1, 0, "Unfilled Form");
this.getField("ProviderOne").setFocus();
}
Thanks a ton for taking the time to read through this, and even more thanks to you if you can help me find a solution.
-Andrew
Figured it out. Instead of grabbing the value using getField("FieldName").value, I grabbed it using .valueAsString. Hopefully this is useful if someone finds it down the road.

Showing matching lines from a search using jquery

I have a bit of code that searches the current information shown on the page from a input source, which is an XML loaded in. This then shows how many times the word has been found, it should then display the lines where the word was found although currently it is showing all the lines. The code is
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", g_playDOM).each(
function() {
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query,
'<span class="query_match">' + query + '</span>');
if (currentLine.search(regex_query) > 0)
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
});
$("#sideInfo").append(
"<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
$(document).ready(function() {
loadPlay();
$("#term_search").focus(function(event) {
$(this).val("");
});
$("#term_search").keypress(function(event) {
if (event.keyCode == 13)
searchResults($("#term_search").val());
});
$('#term-search-btn').click(function() {
searchResults($("#term_search").val());
});
});
</script>
Currently the number of lines the word is on is being shown correctly.
If you want a line of code to be executed within a conditional, then you need to place curly braces around it. Otherwise, only the very next action item will be executed. In your case, increase the count of the number of lines that match.
Your subsequent action item, appending the found line into the DOM is executed on every branch because the if statement has already done its job. Offending lines below:
if ( currentLine.search(regex_query) > 0 ) num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
Fixed:
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++;
$("#mainOutput").append("<p>" + matchesLine + "</p>");
}

Categories