Need to use javascript with try,catch and throw exceptions. I want to use it to check a textbox to make sure it is a number not a letter - javascript

When I add the test function it doesn't work. But when I take out the test function it works but still displays any none numbers as nan.
HTML code:
<h2>How many male books would you like to order? : <input type="text" id ="maleTotal"/>
<input type="button" onClick="maleBook()" Value = "Total" />
<p> The total is: <br>
<span id = "result"></span></h2>
</form>
Javascript code:
function maleBook(){
var malePrice = 14.95;
var tax = .06875;
maleTotal = document.getElementById("maleTotal").value;
totalTax = tax * malePrice * maleTotal
document.getElementById("result").innerHTML = maleTotal * malePrice + totalTax;
}
function test() {
var x;
x = document.getElementById("maleTotal").value;
try {
if(x == "") window.alert "empty";
if(isNaN(x)) window.alert"not a number";
}
catch(err) {
message.innerHTML = "Input is " + err;
}

For one thing, you're missing parenthesis on alerts. It should be like: window.alert("your message");
For another thing, you're missing brackets on if statements {}
Lastly, you need to call the test() function, maybe chain it in at the end of maleBook()
function maleBook(){
var malePrice = 14.95;
var tax = .06875;
maleTotal = document.getElementById("maleTotal").value;
totalTax = tax * malePrice * maleTotal
document.getElementById("result").innerHTML = maleTotal * malePrice + totalTax;
test();
}
function test() {
var x = document.getElementById("maleTotal").value;
try {
if(x == "") {
window.alert( "empty");
}
if(isNaN(x)) {
window.alert("not a number");
}
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}

Like the other guys said you are missing the parenthesis at the alerts and a bracket at catch.
I made a change at your javascript code calling test function before you calculate total tax and it became like this.
And it is just a detail but I am passing maleTotal value as a parameter to test function.
function maleBook(){
var malePrice = 14.95;
var tax = .06875;
maleTotal = document.getElementById("maleTotal").value;
if(test(maleTotal)){
totalTax = tax * malePrice * maleTotal
document.getElementById("result").innerHTML = maleTotal * malePrice + totalTax;
}else{
//put some message here
}
}
function test(x) {
var err= true;
try {
if(x == ""){
window.alert("empty");
err=false;
}
if(isNaN(x)){
window.alert("not a number");
err=false;
}
return err;
}catch(err) {
message.innerHTML = "Input is " + err;
return false;
}
}

First of all, your test function has errors: You are forgetting parethesis next to alert:
alert("some message here");
Also, you dont seem to be calling test(). You sould make test() return true/false depending is the input is a number, and call it in your main function
also "message.innerHTML" doesnt seem to have a meaning here. Just use alert on that as well.

Related

how to run an function if other function return true on focusout

I have 2 inline function calls on focus out event.
I want 2nd function run if 1st function return true without calling the 2nd funtion inside 1st function.
Inside this string 01-Dec-2018 - t57 ( 1 )0 in brackets is available stock quantity.
i have tried the following code but output is not coming.
function checkStockAvailable(batchNo, qty) {
var startpos = batchNo.indexOf("( ");
var endpos = batchNo.indexOf(" )");
var stockQty = batchNo.substring(startpos + 2, endpos);
if (qty > stockQty) {
alert("Entered quantity can not be greater than stock quantity, please try again.");
return false;
}
if (qty <= stockQty) {
return true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" value="10" onfocusout="if((return checkStockAvailable('01-Dec-2018 - t57 ( 1 )0', $(this).val())) == true){saveDetailData('1',$(this).val(),'columnName' )})">
no output shows
function function1(batchNo, qty) {
var startpos = batchNo.indexOf("( ");
var endpos = batchNo.indexOf(" )");
var stockQty = batchNo.substring(startpos + 2, endpos);
if (qty > stockQty) {
alert("Entered quantity can not be greater than stock quantity, please try again.");
return false;
}
if (qty <= stockQty) {
return true;
}
}
function function2(a,b,c){
alert('yes came in function 2');
}
<input type="number" value="10" onfocusout="function1('01-Dec-2018 - t57 ( 1 )0','10') && function2('4','5','6')"/>
You can simplify the call by doing it like this
onfocus="function1() && function2()"
This will run the function2 if function1 returns a truthy value, and ignore function2 if function1 returns a false value.
Check out this fiddle. Try changing the return value from function1 to see the effect.
You could use the data-* global attributes with additional information and use this for a check.
function checkStockAvailable(element) {
var qty = +element.value,
stockQty = +element.dataset.stockQty;
console.log(qty, stockQty);
if (qty <= stockQty) return true;
console.log("Entered quantity can not be greater than stock quantity, please try again.");
}
<input
type="number"
value="10"
onfocusout="checkStockAvailable(this)"
data-batch-no="01-Dec-2018 - t57 ( 1 )0"
data-stock-qty="1"
>
<input type="number" value="10" onfocusout="if(f1()){f2()}">
<script>
function f1() {
return true;
}
function f2() {
alert(4);
}
</script>
you can use onfocusout= "func1() && func()" (as answered by #Shahzad )
func1() will be used for your conditional statement, and func2() will be dependent on func1()
If you are still facing issue, there might be some suntax issue.
function uppercase() {
var x = document.getElementById("tText");
x.value = x.value.toUpperCase();
}
function checkBoolean(){
return true;
}
<input type="text" id="tText" value="test" onfocusout="checkBoolean() && uppercase()">

Passing a variable that is inside a function to other function without changing its value in Javascript

I have 2 functions I would like to know how can I get the variable "foto" that generates a random number inside the function generate() to the function verify() because the indexOf will verify the number that was generated on the generate() function and will check if this value is in one of the arrays defined inside verify().
function generate() {
var score = document.getElementById('score');
var foto = Math.floor(Math.random() *20) + 1;
var fotoDOM = document.querySelector('.foto');
fotoDOM.src = 'foto-' + foto + '.jpg';
console.log(foto);
document.getElementById('photo').style.animation ="appearPerson 1s";
score.innerHTML = foto;
}
document.querySelector('.btn').addEventListener('click', verify);
function verify() {
var yesMeetup = [0,1,2,3,4,5,6,7,8,9,10,12,13,14,15];
var notMeetup = [16,17,18,19,20];
var notButton = document.getElementById('no');
var yesButton = document.getElementById('yes');
var decisao = document.getElementById('decisao');
debugger
if (yesButton) {
if (yesMeetup.indexOf(foto) ) {
decisao.textContent = "You got it";
} else if (notMeetup.indexOf(foto) ) {
decisao.textContent = "wrong";
}
}
else if (notButton) {
if (notMeetup.indexOf(foto) ) {
decisao.textContent = "You Gou it";
} else if (yesMeetup.indexOf(foto) ) {
decisao.textContent = "Wrong";
}
}
}
Declare the foto variable outside of the generate function (which will make it global) and it will be available in the verify function.
I suggest you have a read about closures
var foto;
function generate(){
var score = document.getElementById('score');
foto = Math.floor(Math.random() *20) + 1;
var fotoDOM = document.querySelector('.foto');
fotoDOM.src = 'foto-' + foto + '.jpg';
console.log(foto);
document.getElementById('photo').style.animation ="appearPerson 1s";
score.innerHTML = foto;
}
document.querySelector('.btn').addEventListener('click', verify);
function verify()
{
var yesMeetup = [0,1,2,3,4,5,6,7,8,9,10,12,13,14,15];
var notMeetup = [16,17,18,19,20];
var notButton = document.getElementById('no');
var yesButton = document.getElementById('yes');
var decisao = document.getElementById('decisao');
debugger
if(yesButton){
if(yesMeetup.indexOf(foto) ){
decisao.textContent = "You got it";
}else if(notMeetup.indexOf(foto) ){
decisao.textContent = "wrong";
}
}
else if (notButton){
if(notMeetup.indexOf(foto) ){
decisao.textContent = "You Gou it";
}else if(yesMeetup.indexOf(foto) ){
decisao.textContent = "Wrong";
}
}
}
If the value of foto is required by the function verify, then that should be an argument of that function:
document.querySelector('.btn').addEventListener('click', function() {
var foto = generate();
verify(foto);
});
...
/**
* Generate a thing.
*/
function generate() {
...
return foto;
}
/**
* Veryify the thing.
* #param {Number}
*/
function verify(foto) {
...
}
I would encourage you to insulate your functions as much as possible so that they don't really depend on outside variables. Maybe manipulating DOM is required inside one of them, but if you can abstract those things away from each other – DOM manipulation in 1 function or bit of code, and all other business logic in another set of functions, your code should be easier to read / write / debug.

Call 2 functions in is

I have 2 functions that work fine on their own. Using them in a form. I can call them in one onclick event, however I would like to place both in one script with the first called validate() but only call second function display() if information is correct. So if validate() is called and info not correct they get an alert and returns to form true, if info correct then display() is called. Any help appreciated.
function validate() {
// Get the value of the input field with id="QTY"
var x = document.forms["confirm"]["QTY"].value;
// If x is Not a Number or less than one
if (isNaN(x) || x < 1 ) {
alert("Quantity - Minimum 1 required please");
return true;
}
}
function display()
{
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
var confirm = window.confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?' );
}if(result)
{
// user has pressed ok
}
else
// user has pressed cancel
{
document.getElementById("myform").reset();
}
It is customary to have validate return true if the validation passes.
function validate() {
// Get the value of the input field with id="QTY"
var x = document.forms["confirm"]["QTY"].value;
// If x is Not a Number or less than one
if (isNaN(x) || x < 1 ) {
alert("Quantity - Minimum 1 required please");
return false;
}
return true;
}
function display()
{
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
var confirm = window.confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?' );
if(confirm)
{
// user has pressed ok
}
else
// user has pressed cancel
{
document.getElementById("myform").reset();
}
}
if (validate()) { display(); }
If you give us more information about the html and glue code we could help better.

Object function not working in JS

This is a function for a simple shopping app (kinda) thing that I coded to work on my JS skills, considering my elementary experience in it. But everything works except for one thing:
The applyStaffDiscount function doesn't seem to work. Everytime I try to apply an employee discount, the program just returns the same original value that was present before trying to apply the discount. Please help and also let me know how I can improve this program.
function StaffMember(name, discountPercent) {
this.name = name;
this.discountPercent = discountPercent;
}
var sally = new StaffMember("sally", 5);
var bob = new StaffMember("bob", 10);
var arhum = new StaffMember("arhum", 20);
var cashRegister = {
total: 0,
lastTransactionAmount: 0,
add: function(itemCost) {
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item, quantity) {
switch (item) {
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction: function() {
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
applyStaffDiscount: function(employee) {
this.total -= (this.total * (employee.discountPercent/100))
}
};
var cont = confirm("Are you ready to shop?")
while (cont) {
var user = ("Choose your function: A to Add Item, ED for Employee Discount, VT to Void Transaction or just X to Close")
var askUser = prompt(user).toUpperCase()
if (askUser === "A") {
var itemName = prompt("What item would you like?", "Eggs, Milk, Magazine, Chocolate").toLowerCase()
var itemNum = prompt("How many?")
cashRegister.scan(itemName, itemNum)
var cont = confirm("Your total bill is $" + cashRegister.total.toFixed(2) + ". Would you like anything else?")
}
else if (askUser === "ED") {
var name1 = prompt("Please enter you name").toLowerCase()
cashRegister.applyStaffDiscount[name1]
alert("Your total bill is $" + cashRegister.total.toFixed(2) + ".")
}
else if (askUser === "VT") {
cashRegister.voidLastTransaction()
alert("Your previous transaction has been voided. Your total bill is $" + cashRegister.total.toFixed(2) + " now.")
}
else if (askUser === "X") {
cont = false
}
if (cont === false) {
alert("We hope you had a good time. have a nice day!")
}
}
calling applyStaffDiscount should be done as shown below
cashRegister.applyStaffDiscount(name1);
Then inside applyStaffDiscount function, it should be accessed as below
this.total -= (this.total * (window[employee].discountPercent/100))
You didn't call the function in here:
cashRegister.applyStaffDiscount[name1]
Try it with something like this:
cashRegister.applyStaffDiscount(name1);

javascript 101: sales tax calculator does not respond to data entry

I'm guessing the onload function is not properly implemented. Entering numbers or letters do not get the appropriate error or calculation response.
This is my code as of now:
http://jsfiddle.net/907yn57r/
var $ = function (id) {
return document.getElementById(id);
}
var calculateTaxAndTotals = function () {
var taxRate = parseFloat($("taxRate").value); //The tax rate, as a percentage (e.g. 8.5)
var subTotal = parseFloat($("itemPrice").value); //An item price ex $5.95
$("salesTax").value = "";
$("totalItemCost").value = "";
if (isNaN(taxRate) || taxRate <= 0) {
document.taxCalc.taxRate.focus();
document.$("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
} else if (isNaN(itemPrice) || itemPrice <= 0) {
document.$("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
} else {
var salesTax = subTotal * (taxRate / 100);
var totalItemCost = salesTax + itemPrice;
$("orderTotal").focus();
alert(totalItemCost);
}
}
window.onload = function () {
calculateTaxAndTotals();
}
There are a couple of problems.
First of all, JSFiddle deals with the main html structure itself, so you don't need new body tags and the like.
Secondly, the Javascript here needs to be loaded in the head or the body (on the top left in JSFiddle you can choose different places for it to be loaded).
Finally, there's a few errors in the definition for CalculateTaxAndTotals, it should say
if (isNaN(taxRate) || taxRate <= 0) {
document.taxCalc.taxRate.focus();
$("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
} else if (isNaN(subTotal) || itemPrice <= 0) {
$("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
} else {
var salesTax = subTotal * (taxRate / 100);
var totalItemCost = salesTax + itemPrice;
$("orderTotal").focus();
alert(totalItemCost);
}
Really Fixed Fiddle
The final issue was that you were calling isNaN on itemPrice, but the variable itemPrice didn't exist.

Categories

Resources