Control sum from input boxes in javascript - javascript

I'm trying to make some controls in Javascript when I submit a form in HTML.
Evertyhing works perfectly except the one that needs to check the sum of 2 fields.
<script type="text/javascript">
function validation()
{
var count=0;
if((document.getElementsByName("people")[0].selectedIndex) == "")
{alert("How many PEOPLE?"); count++;}
else if((document.getElementsByName("amount")[0].selectedIndex) == "")
{alert("AMOUNT has to be at least 1."); count++;}
else if((document.getElementsByName("deposit")[0].value) == "")
{alert("DEPOSIT cannot be empty."); count++;}
else if((document.getElementsByName("deposit")[0].value) < "20")
{alert("DEPOSIT must be at least 20."); count++;}
else if((document.getElementsByName("topay")[0].value) == "")
{alert("Mark 0 in TO PAY if they dont have to pay more."); count++;}
else if( ( (document.getElementsByName("deposit")[0].value) + (document.getElementsByName("topay")[0].value) ) < "40")
{alert("The minimum price of this product is 40"); count++;}
else if((document.getElementsByName("seller")[0].value) == "")
{alert("Who is the SELLER?"); count++;}
else if(isNaN(document.getElementsByName("topay")[0].value))
{alert("TO PAY must be a number"); count++;}
else if(isNaN(document.getElementsByName("people")[0].value))
{alert("PEOPLE must be a number"); count++;}
else if(isNaN(document.getElementsByName("deposit")[0].value))
{alert("DEPOSIT must be a number"); count++;}
else if(isNaN(document.getElementsByName("amount")[0].value))
{alert("AMOUNT must be a number"); count++;}
return (count==0);
}
</script>
The one that I'm not able to solve is:
else if( (((document.getElementsByName("deposit")[0].value) + (document.getElementsByName("topay")[0].value)) < "40)")
{alert("The minimum price of this product is 40"); count++;}
I want it to check if (deposit + topay) < 40. I noticed that with this code it is just checking if (deposit < 40) and I don't understand why.
Can you please help me?

The '+' operator acts as concatenation operator in a conditional statement(or generally performs concatenation).
Hence to make it perform addition operation use,
else if( ((parseInt(document.getElementsByName("deposit")[0].value) + parseInt(document.getElementsByName("topay")[0].value)) < 40))
{alert("The minimum price of this product is 40"); count++;}

var abc = parseInt(
(document.getElementsByName("deposit")[0].value)+(document.getElementsByName("topay")[0].value)
) if( abc < "40" ) { alert("h"+abc); }

change your if condition to this
if( (((document.getElementsByName("deposit")[0].value) + (document.getElementsByName("topay")[0].value)) < 40))

Related

JavaScript if/else statement that makes a user enter a value

How would you make an if/else statement loop back to the beginning to get user information?
This is the code I got so far:
var age = prompt("Please enter your age");
if(age == 21 ) {
alert("Happy 21st Birthday!");
} else if (age > 21 ) {
alert("You are old");
} else {
alert("Please enter an age");
}
I'm trying to make it go back to the beginning to make the user enter information.
var age = '';
while(age == '' || age == 'ok'){
age = prompt("Please enter your age");
if($.isNumeric(age) === false){
continue;
}
if(age == 21 ){
alert("Happy 21st Birthday!");
continue;
}
if (age > 21 ){
alert("You are old");
continue;
}
if (age < 21){
alert("You are too young to be in this bar!");
}
}
for (let age = prompt('Please enter your age'); ;) {
if (age == 21) {
alert('Happy 21st Birthday!');
break;
} else if (age > 21) {
alert('You are old');
break;
} else {
age = prompt('Please enter your age');
}
}
You separate validation logic from the user input logic.
If this is console app then you would place a loop around the prompt and then validate the user age, if the age is valid break out of the loop otherwise let the loop continue.
On a web page you would wrap it in a function and based on the result manipulate the view based on if the age is correct or not. So you would perhaps show an error message if the age is invalid or go to the next page if the age is valid.
You should wrap the if statements which make up the validation logic in into a function perhaps validateAge that returns true or false, that way no matter what you implement you can use the same method.
Working off of #wallyk's suggestion using a while loop yields this example:
var age = false;
while (!age) {
age = prompt("Please enter your age");
if (age == 21) {
alert("Happy 21st Birthday!");
} else if (age > 21) {
alert("You are old");
} else if (!!age && age < 21) {
alert("You are young");
} else {
alert("Please enter an age");
age = false;
}
}
It will keep looping until you type a valid number answer. I also added in a check to see if the user input an age under 21, since I'm guessing you don't want to keep looping forever if the user is under 21 (or keep looping until they turn 21) but that part can easily be removed if you want.

If/Else Statement

Hi what am I doing wrong with this if statement? Ive tried making the second one and else if and the last one an else as well but cant get the alerts to respond properly.
prompt("Please enter a number");
if(x < 100) {
alert("variable is less 100")
}
if(x == 100) {
alert("variable is equal to 100!")
}
if(x > 100) {
alert("variable was greater than 100")
}
thanks!
You are missing an assignment to variable x.
var x = prompt("Please enter a number");
//^^^^^
Then you could use parseInt to get a integer number from the string
x = parseInt(x, 10);

JavaScript Validation Else If not working - alert for If is, else is not

So I'm making a dynamic table which takes inputs for values of a Miles to Kilometers table. My HTML works fine, and my functions for the displaying of the table works fine, however when adding validation to this to make sure that negative Integers cannot be inputted, the if statement in my for loop works, but the else statements break the code. I am extremely confused as to why.
Here is my JS code:
for (var i = from; i <= to; i++) {
tr = document.createElement("tr");
if (i <= -1)
alert("Value must be positive Integer");
else if (i % 2 == 0)
tr.setAttribute("class", "even");
else
tr.setAttribute("class", "odd");
It is the if else which does not work. I'd be grateful for some help!
Please try this
if (i <= -1){
alert("Value must be positive Integer");
return false;
}
else if (i % 2 == 0)
tr.setAttribute("class", "even");
else
tr.setAttribute("class", "odd");
Using break;
if (i <= -1)
alert("Value must be positive Integer");
break;
else if (i % 2 == 0)
tr.setAttribute("class", "even");
else
tr.setAttribute("class", "odd");
if (from > -1 && to>=from) {
for (var i = from; i <= to; i++) {
tr = document.createElement("tr");
if (i % 2 == 0)
tr.setAttribute("class", "even");
else
tr.setAttribute("class", "odd");
}
else{
alert("Value must be positive Integer");
}

How to get alerts for inputed name length of characters - javascript

Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/

JavaScript - how to validate field to allow certain character and certain length

I need to validate a textbox, so it's value consist of 10 characters (not more, not less). The below code does it, allowing me to set the restricted length for each field separately.
function charLength(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
alert("Invalid number of characters");
elem.focus();
return false;
}else{
return true;
}
}
and this is how I'm calling it:
onBlur="charLength(document.getElementById('tf1'),1,9)"
but the field that I validate must not only be 10 characters long, but it also has to start with letter Z.
How would I do such validation? is it possible in the first place?
try it also:
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max && uInput.substr(0, 1) == "Z"){
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
else return true; //i
}
and try to add maxlength in the textbox
<input type="text" maxlength="10">
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length == 10 && uInput.substr(0, 1) == "Z")
return true;
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
function charZ10(elem) {
var pass = /^Z.{9}$/.test(elem.value); // 10 chars starting with Z
if (!pass) {
alert("Try again, noob.");
elem.focus();
}
return pass;
}
Must be
if(uInput.length <= 10 && substr(uInput,0, 1) == "Z")

Categories

Resources