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.
Related
Notes Domino web form, validating onblur what was entered in a field. Field is set as a number but I want to catch what was entered immediately if it is not a number. Then I want to clear what was entered and put the focus right back in the field. I get the code to run, and the alert comes up correctly but the focus does not happen, nor does the value get removed.
function checkNumeric(fld, nm) {
debugger;
var x;
x = document.getElementById(fld).value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x)) {
document.getElementById(fld).value = '';
alert("Non-numeric entry of '" + x + "' in : " + nm +", please try again.");
document.getElementById(fld).focus();
}
}
Be also sure that the event handler which calls this is set to prevent default. Otherwise it might be the element get the focus but is removed afterwards by the event handler emediatly.
function checkNumeric(fld, nm) {
//debugger;
var x;
if (typeof fld !== "string") {
alert("fld is not a string");
}
if (typeof nm !== "string") {
alert("nm is not a string");
}
var elm = document.getElementById(fld);
if (elm) {
x = elm.value;
if (isNaN(x)) {
elm.value = '';
alert("Non-numeric entry of '" + x + "' in : " + nm + ", please try again.");
elm.focus();
}
}
}
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.
I am using App Lab on Code.org, which utilizes JavaScript commands; however, they have their own UI controls. Therefore, the code will contain commands such as onEvent() and setText(), etc. etc. These are all acceptable. I am attempting to make a code for the Spherical Law of Cosines, but my output for the number is printing NaN. What does this mean and how can I fix it?
Part of my code is below:
onEvent("outputgoScrn","click",function(){
setScreen("outputScrn");
setText("output","The distance between these two locations is " + ((Math.acos((Math.cos(a)*(180/Math.PI))*(Math.cos(b)*(180/Math.PI)) + (Math.sin(a)*(180/Math.PI))*(Math.sin(b)*(180/Math.PI)) + (Math.cos(N)*(180/Math.PI))*(180/Math.PI)))) + " miles along the Great Circle.");
});
onEvent("lat1", "change", function() {
var choice = getProperty("lat1","value");
if(choice=="N") {
a = 90 - ((getNumber("lat1deg")+(getNumber("lat1min")/60)));
}
else if(choice=="S") {
a = 90 + (getNumber("lat1deg")+(getNumber("lat1min")/60));
}
});
onEvent("lat2", "change", function() {
var choice = getProperty("lat2","value");
if(choice=="N") {
b = 90 - ((getNumber("lat1deg")+(getNumber("lat1min")/60)));
}
else if(choice=="S") {
b = 90 + (getNumber("lat2deg")+(getNumber("lat2min")/60));
}
});
onEvent("lon1", "change", function() {
var choice = getProperty("lon1","value");
onEvent("lon2","change",function() {
var choice2 = getProperty("lon2","value");
if(choice=="E" && choice2=="E") {
N = (getText(("lon1deg")+(getText("lon1min")/60))) - (getText(("lon2deg")+(getText("lon2min")/60)));
}
else if(choice=="W" && choice2=="W") {
N = getText(("lon1deg")+(getText("lon1min")/60)) - getText(("lon2deg")+(getText("lon2min")/60));
}
else if(choice=="W"&&choice2=="E") {
N = getText(("lon1deg")+(getText("lon1min")/60)) + getText(("lon2deg")+(getText("lon2min")/60));
}
else if(choice=="E"&&choice2=="W") {
N = getText(("lon1deg")+(getText("lon1min")/60)) + getText(("lon2deg")+(getText("lon2min")/60));
}
});
});
NaN stands for "Not a Number". It looks like you are trying to do arithmetic operations with strings. You need to parse your string to number
var text = '42px';
var integer = parseInt(text, 10);
// returns 42
For more parse functions, you can check below link
https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/
I want to get the value of the input with id ticketNum and alert that when clicked. I got that working. I also want to compare the number to 10 if the value is a number using < and >.
The first alert is working fine but the second is not:
function initElement() {
var p = document.getElementById("sub");
p.onclick = showAlert;
};
function showAlert() {
var o = document.getElementById("ticketNum").value;
alert('la valeur de cet input est ' + o);
if (typeof o === "number") {
if (o < 10) {
alert('inferieur a 10');
} else {
alert('superieur a 10');
}
}
};
For checking whether given text input is number or not you can use isNaN function and then convert it to number using Number function.
Here's sample code snippet based on question -
function initElement() {
var p = document.getElementById("sub");
p.onclick = showAlert;
};
function showAlert() {
var o = document.getElementById("ticketNum").value;
alert('the input value is ' + o);
if (!isNaN(o)) {
if (Number(o) < 10) {
alert('inferior to 10');
} else {
alert('superior to 10');
}
}
};
initElement();
<input id="ticketNum" type="text" />
<button id="sub">Show Alert</button>
How do i count #total value + 170 with jquery?
$("#member").click(function() {
if ($('#member').is(':checked')) {
var totalv = $("#total").val();
var skatz = 170;
var skaits = totalv + skatz;
$("#total").val(skaits);
}
You should check if the provided value is actually a number (You can do onkeypress or keyup each time but I say you should always check on submission). Below is your code modified to work (With checks to see if the value is a number).
EDIT: Make sure that your javascript has document ready wrapped around it. (Functions can be outside of this call)
$(document).ready(function () {
$("#member").click(function() {
if ($('#member').is(':checked')) {
var totalv = $("#total").val();
if(isNumber(totalv) == true)
{
var skatz = 170;
var skaits = parseInt(totalv) + skatz;
$("#total").val(skaits);
}
else
{
alert("You must enter a numerical value");
}
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
The result of .val() will be a string, so you first need to convert it to a number:
var totalv = $("#total").val();
var skatz = 170;
var skaits = +totalv + skatz;
$("#total").val(skaits);
(notice the additional + prefix to the totalv variable.