Javascript conditional statements with range input values - javascript

could someone help me with the following Javascript code. I want the conditional statements to execute if the value of "score" is between the ranges of 1-3, 3-5, 5-7, 7-9 and 9-10.
Currently, they only execute if the variable "score" is an integer, but I want the scores to be executed between the range of numbers.
for example, I want the line "if ((score==1) || (score==2) || (score==3))" to be something like if( score is between 1 and 3), Then the statement will be executed.
This is the HTML:
Input 1 <input type="number" id="num1">
<br>
<br>
Input 2 <input type="number" id="num2">
<br>
<br>
Input 3 <input type="number" id="num3">
<br>
<br>
Input 4 <input type="number" id="num4">
<br>
<br>
Input 5 <input type="number" id="num5">
<br>
<br>
<button onclick="calculate()">Calculate</button>
<h1 id="answer"></h1>
<h1 id="advice"></h1>
This is the JS:
function calculate()
{
var field1=document.getElementById("num1").value;
var field2=document.getElementById("num2").value;
var field3=document.getElementById("num3").value;
var field4=document.getElementById("num4").value;
var field5=document.getElementById("num5").value;
if ( (field1>10) || (field1<1)|| (field2>10) || (field2<1) || (field3>10) || (field3<1) || (field4>10) || (field4<1) || (field5>10) || (field5<1))
{
alert("Enter a number between 1 and 10");
return false;
}
var result=parseFloat(field1)+parseFloat(field2)+parseFloat(field3)+parseFloat(field4)+parseFloat(field5);
var score= result / 5;
if ((score==1) || (score==2) || (score==3))
{
document.getElementById("advice").innerHTML="You are between 1 and 3";
}
if ((score==4) || (score==5))
{
document.getElementById("advice").innerHTML="You are between 4 and 5";
}
if ((score==6) || (score==7))
{
document.getElementById("advice").innerHTML="You are between 6 and 7";
}
if ((score==8) || (score==9))
{
document.getElementById("advice").innerHTML="You are between 8 and 9";
}
if ((score==10))
{
document.getElementById("advice").innerHTML="You are 10";
}
if(!isNaN(score))
{
document.getElementById("answer").innerHTML="Your career score is " + score;
}
}
Help will be super appreciated!

if (score >= 1 && score < 3) {
// do something
} else if (score >= 3 && score < 5) {
// do something
}
... and so on

Also I would like to help you write better code:
This:
if ( (field1>10) || (field1<1)|| (field2>10) || (field2<1) || (field3>10) || (field3<1) || (field4>10) || (field4<1) || (field5>10) || (field5<1))
{
alert("Enter a number between 1 and 10");
return false;
}
And more cleaner code:
const fault = [field1, field2, field3, field4, field5].find(el => {
if (el < 1 || el > 10) { // if we find this, then fault will be the index of this element
return true
} else { return false } // else fault will be undefined
})
if (fault) {
alert("Enter a number between 1 and 10")
return false
}

Related

decimal places auto format in price jquery

i am trying to covert decimal places on type input field like
Number starts from 0.00
so at first place it will be 0.00 in input field
than i type 1 than it should become 0.01
than i type 2 than it should become 0.12
than 0 so it should become 1.20 and lastly
when i type 0 than it should become 12.00
0.01, 0.12, 1.20, 12.00.
I tried some methods which already given in SO but not successful.
Please suggest me another methods if possible. thank you.
i tried like this
$(document).on('keyup','.price',function(e){
var value = $(this).val();
if(value.length <= 6) {
if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
var amountDots = 0;
var amountCommas = 0;
if(value.indexOf(',') > -1){
amountCommas = value.match(/,/gi).length;
}
if(value.indexOf('.') > -1){
amountDots = value.match(/./gi).length;
}
if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
$(this).val(value.substr(0,value.length - 1));
return false;
}
else{
$(this).val(value.substr(0, value.length - 1) + ',');
}
}
$(this).val(value/100); //here is the value will insert
} else {
$(this).val(value.substr(0,value.length - 1))
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="price" />
Ok, totally different solution that works when deleting characters:
$(document).on('keypress','.price',function(e){
var char = String.fromCharCode(e.which);
if(isNaN(char)) char = '';
var value = $(this).val() + char;
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
var value = $(this).val();
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
});
https://jsfiddle.net/14shzdo5/
With each new keystroke, assuming it's a number, append it to the end, multiply by 10 and display the result.
The following logic works for the basic scenario. You may have to separately handle clearing out the text input.
$(document).ready(function() {
$("#my-input").on('keyup', function(e) {
var v = String.fromCharCode(e.keyCode);
if (!isNaN(v)) {
var dv = $("#my-display").val();
$("#my-display").val(dv + '' + v);
$(this).val(($("#my-display").val() / 100).toFixed(2));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="my-input" />
<input type="hidden" id="my-display" />

Write a JavaScript conditional statement to find the sign of product of three numbers. Display an alert box with the specified sign

I want to write a JavaScript conditional statement to find the sign of product of three numbers. Display an alert box with the specified sign. The three numbers have to be written in input fields. And when I click on an OK button, it should tell me what sign of product I have. Is it a postive number(+) or negative(-)?
<body>
Please enter numbers that aren't 0.
<input id="x" type="text" name="" value="">
<input id="y" type="text" name="" value="">
<input id="z" type="text" name="" value="">
<button type="onclick" onclick="value()" name="button">OK</button>
<script>
function value() {
document.getElementById('x').innerHTML;
document.getElementById('y').innerHTML;
document.getElementById('z').innerHTML;
if (x>0 && y>0 && z>0)
{
alert("The sign is +");
}
else if (x<0 && y<0 && z<0)
{
alert("The sign is +");
}
else if (x>0 && y<0 && z<0)
{
alert("The sign is +");
}
else if (x<0 && y>0 && z<0)
{
alert("The sign is +");
}
else
{
alert("The sign is -");
}
}
</script>
</body>
</html>
Why not multiply them then set the condition on the product?
const x = document.getElementById('x').value;
const y = document.getElementById('y').value;
const z = document.getElementById('z').value;
const product = x*y*z;
let sign = (product < 0) ? '-' : '+';
sign = (product === 0) ? 'Neither' : sign;
alert(sign);
You should parse value of input fields using
var x = Number("Your input field");
Then Your variable will be treated as integer and Your condition of bigger or smaller than 0 will work.
Input elements have a value not, innerHTML
Even if you would have corrected that, you will not have values, since you did not assign them to any variable
For number only input use the number type, this will prevent someone from entering not numeral characters (in all modern browsers)
document.getElementById('check-value').addEventListener('click', (e) => {
const x = document.getElementById('x').value;
const y = document.getElementById('y').value;
const z = document.getElementById('z').value;
if (x + y + z >= 0) {
alert("The sign is +");
} else if (x < 0 && y < 0 && z < 0) {
alert("The sign is +");
} else if (x > 0 && y < 0 && z < 0) {
alert("The sign is +");
} else if (x < 0 && y > 0 && z < 0) {
alert("The sign is +");
} else {
alert("The sign is -");
}
});
Please enter numbers that aren't 0.<br>
<input id="x" type="number" name="" value="">
<input id="y" type="number" name="" value="">
<input id="z" type="number" name="" value="">
<button type="button" id="check-value" name="button">OK</button>

Why is my switch not working?

I have a switch statement to give you a letter mark if you enter a number mark. I am not getting any errors from chrome so i don't know what i am doing wrong. Would i be just formatting it wrong?
<html>
<body>
<h1>Rank Your Mark!!</h1>
Enter your mark to rank it.
<input type="number" name="grade" id="mark">
<input type="button" name="mark" id="grade" value="Rate" onclick="rateMark()">
<script>
function rateMark(){
switch(grade)
{
case"F":
mark > 50;
break;
case"D":
mark >= 50 && mark <=59.9;
break;
case"C":
mark >= 60 && mark <=69.9;
break;
case"B":
mark >= 70 && mark <= 79.9;
break;
case"A":
mark >= 80 && mark <= 89.9;
break;
case"A+":
mark >= 90 && mark <= 100;
break;
}
document.getElementById("demo").innerHTML = "You got a" + mark;
}
</script>
<br>
<p id="demo"></p>
</body>
</html>
You're not using the right way, check how it works here.
What you're doing is compare if grade variable is "F", "D", "C".....
Use if and else if and put your statements into them, like this:
var mark = document.getElementById('mark').value // gets the input value to "mark" variable
if(mark >= 70 && mark <= 79.9){
// do something here
} else if(mark >= 80 && mark <= 89.9){
// do another thing here
}
so on...
See this:
<body>
<h1>Rank Your Mark!!</h1>
Enter your mark to rank it.
<input type="number" name="grade" id="mark">
<input type="button" name="mark" id="grade" value="Rate" onclick="rateMark()">
<script>
function rateMark(){
mark = document.getElementById("mark").value
if (mark < 50) {
mark = "F"
} else if (mark >= 50 && mark <=59.9) {
mark = "E"
} else if (mark >= 60 && mark <=69.9) {
mark = "D"
} else if (mark >= 70 && mark <= 79.9) {
mark = "C"
} else if (mark >= 80 && mark <= 89.9) {
mark = "B"
} else if (mark >= 90 && mark <= 100) {
mark = "A"
}
document.getElementById("demo").innerHTML = "You got a " + mark;
}
</script>
<br>
<p id="demo"></p>
</body>

Need a If and else statement and a new page

This is what i need help with!
My project needs a If and else statement for the Age part!
and then send the person who has validated correctly to a new page.. I currently have a page but that is just something that is in my USB
also need to explain how its is validating
Please help
!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "")
{
alert("Name must be filled out");
return false;
}
var Age = document.forms["myForm"]["Age"].value;
if (Age == null || Age == "") {
alert("Has to be a number between 1 and 150");
return false;
}
var Email = document.forms["myForm"]["Email"].value;
if (Email == null || Email == "") {
alert("Make sure it is the correct Email format");
return false;
}
var myCheck = document.getElementById("check1").checked;
if (myCheck == false) {
alert("Have to tick box to proceed");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="file:///G:/Welcome.html"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="Age">
Email: <input type="text" name="Email">
<br>checkbox: <input type="checkbox" id="check1" name="myCheck"> </br>
<input type="submit" value="click">
</form>
</body>
</html>
You could extend the if clause with the age check.
var age = document.forms["myForm"]["Age"].value;
if (age == "" || age < 1 || age > 150) {
// ^^^^^^^^^^^^^^^^^^^^^^^
alert("Has to be a number between 1 and 150");
return false;
}
I'd parse the value of the form into a number and then I'd check its range:
var age = Number(document.forms["myForm"]["Age"].value) || 0;
if (age < 1 || age > 150) {
alert("Has to be a number between 1 and 150");
return false;
}
Why convert to number and put Number(document.forms["myForm"]["Age"].value) || 0?
The reason is simple: imagine that a malicious user put in your form the value "NaN". If you didn't do this check, the value of age would be NaN and it'd pass your check (NaN < 1 is false and NaN > 150 is false too).
This way, if a user put "NaN" in the form, the guard would transform it into 0, the alert would trigger and the function would return false.

Validate and display window alert

how do I validate to ensure a value for total or orderForm have been fill up if not it will display a window alert upon clicking on Submit button ?
It seems the below is not working at all .
Pure JS:
function va(){
var result = false;
var w = document.forms["orderForm"]["companyName"].value;
var x = document.forms["orderForm"]["forename"].value;
var y = document.forms["orderForm"]["surname"].value;
var z = document.forms["orderForm"]["total"].value;
if (x == null || x == "") && (y == null || y == "") && (w == null || w == ""){
window.alert('Name must be Filled out');
result = false;
// } else if (z = < 5){
// window.alert('Please Select A CD');
// return false;
// }else {
// return true;
}
return result;
}
HTML:
<section id="checkCost">
<h3>Total cost</h3>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
<section id="placeOrder">
<h3>Place order</h3>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails" style="display:none">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
try this:
if (x == null || x == "") {
window.alert('forename must be Filled out');
result = false;
} else if (y == null || y == "") {
window.alert('surname must be Filled out');
result = false;
} else if (w == null || w == "") {
window.alert('companyName must be Filled out');
result = false;
}
return result;
Try:
if ((x == null || x == "") || (y == null || y == "") || (w == null || w == ""))
EDIT:
Sure thing, original line:
if (x == null || x == "") && (y == null || y == "") && (w == null || w == "")
I did two things. Switch out the && for || and wrap the if condition in an inclusive set of parenthesis (which probably isn't required but I do it for neatness). The original if statement reads as "if condition and condition and condition" meaning all conditions have to return true (i.e. be blank) in order to continue. I believe each of these values are required to validate the form. My proposed if statement would read "if condition or condition or condition" letting the alert box be displayed if any value is empty.

Categories