The first prompt shows up, and nothing else happens, even if I enter a number or try to push through the prompt without entering anything.
So far I've written this code:
var ratingEntry = prompt("We would like for you to review . Please enter a
rating between 0.0 - 5.0?");
if (ratingEntry === undefined) {
prompt('Please enter a rating from 0-5!');
} else if (ratingEntry === 0) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
} else if (ratingEntry === 1) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
}
I've tweaked it several times to no avail.
The problem you have is that prompt return a string and you do check for equality without type coersion.
1 === 1 is true
"1" === 1 is false
Basically "1" is a string, and 1is a integer.
Change ===to == and you would ignore "type" check. Or just check for "1" instead of 1
To compare Integer you need to first parse ratingEntry into Integer then compare and for first condition It is coming blank not undefined so put both check with OR in first condition.
var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
if (typeof ratingEntry === undefined || ratingEntry.trim() == '') {
prompt('Please enter a rating from 0-5!');
} else if (parseInt(ratingEntry) === 0) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
} else if (parseInt(ratingEntry) === 1) {
teacherRatings.push('ratingEntry');
prompt('Thank you!');
}
and last thing I am not sure what you are doing with this code but It should be like this
Use
teacherRatings.push(ratingEntry);
Instead of
teacherRatings.push('ratingEntry'); //this push ratingEntry as string in teacherRatings not as a value of variable
You may want to parse the input to Float and then use a while loop until the input is valid:
var ratingEntry = prompt("We would like for you to review . Please enter a rating between 0.0 - 5.0?");
var ratingNum = parseFloat(ratingEntry)
while (isNaN(ratingNum) || ratingNum < 0 || ratingNum > 5) {
ratingNum = parseFloat(prompt('Please enter a rating from 0-5!'));
}
teacherRatings.push(ratingNum);
prompt('Thank you!');
A prompt will return a string. And you need to always capture it to compare, so I would do:
var message = "We would like for you to review . Please enter a rating between 0.0 - 5.0?";
while(ratingEntry = prompt(message)) {
if (ratingEntry === '' || ratingEntry < 0 || ratingEntry > 5) {
message = 'Please enter a rating from 0-5!');
} else {
break;
}
}
etc. because you are using === which compares value as well as type (e.g. 1 === 1 and 1 !== '1', but 1 == '1')
Related
I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function
I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)
Friends, i can't figure it out how to add text validation for admin var.
Point is user enters either 0 or 1 or true or false in the form. It's ok with checking numbers but i can't make up valid check for text input, e.g. true-e-e-e, fasleee, abra-cadabra, etc.
<script type="text/javascript">
function submitEmployeeForm() {
// getting the employee form values
var name = $('#name').val().trim();
var age = $('#age').val();
var admin = $('#admin').val();
if(name.length ==0) {
alert('Please enter name');
$('#name').focus();
return false;
}
if(age <= 0) {
alert('Please enter valid age');
$('#age').focus();
return false;
}
if(admin < 0 || admin > 1) {
alert('Please enter 0 for false, 1 for true');
$('#admin').focus();
return false;
}
return true;
};
</script>
I tried the following 2 options:
!admin.isEqual("false") || !admin.isEqual("true")
admin.valueOf()!="true" || admin.valueOf()!="false"
as a result is it does not pass any text including true and false.
If you want to accept only '0','1','true','false' as valid then use something like this
if (['0','1','false','true'].indexOf(admin.toLowerCase()) === -1) {
alert('Please enter 0 for false, 1 for true');
$('#admin').focus();
return false;
}
What we do is create an array which holds the valid texts, and then use indexOf(parameter) which searches the array for any element matching the passed parameter. If it is found it returns the position it was found in the array, if not it returns -1. So in your case if it is -1 which means that the passed value was not one of the accepted then do your thing.
Alternatively, you could use a checkbox instead of a text box, and just test if it is checked property is true.
Just try the following:
if (admin == true || admin == false || admin == "true" || admin == "false") {
//if you want to convert -> convert it, and send to server
} else {
//Wrong input
}
(More at here.
This is an equality table for values if you use == instead of ===)
why you don't just check if it's 1, 0, true or false but using logical AND like this:
if(admin != 0 && admin != 1 && admin != "true" && admin != "false"){
alert('Please enter 0 for false, 1 for true');
$('#admin').focus();
return false;
}
i got a problem on validate the student ID, it require 10 numbers, the problem i met is when i key in a valid student ID, it still return false. Please help me to check mycoding, thank you very much.
example of my Student ID = "1101106363"
if ((document.appsub.id.value == "") || !(isNaN(document.appsub.id.value)) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
update: [link]http://jsfiddle.net/rVswq/1/
You need to use document.getElementById method to select the element properly.
var el = document.getElementById("yourid");
if (!(isNaN(el.value)) || (el.value.length < 11))
{
alert("Please enter the correct Student ID");
el.focus();
return false;
}
There is something strange here.
You are checking if the value is null, OR if it IS a number (isNaN returns true if the value IS NOT a number, if you place !isNaN the result is true if the value IS a number), OR if the length is inferior to 11.
If you want to be sure that the inserted value is not null, a number and its length inferior to 11 you should write
if ((document.appsub.id.value == "") || isNaN(parseInt(document.appsub.id.value)) || (document.appsub.id.value.length > 10))
It looks to me like you don't need the NOT operator
if ((document.appsub.id.value == "") || isNaN(document.appsub.id.value) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your IF statement is wrong. You want:
if ( (document.appsub.id.value == "") || (isNaN(document.appsub.id.value)) || document.appsub.id.value.length < 11) )
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your if statement will catch students ids with length less to or equal to 10.
Test against length like 10 instead
I am very new to JavaScript, and trying to learn using lynda.com.
I'm currently playing around with the if statement.
The code in question:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
if ( value == 2 ) {
alert("You have chosen 2.");
}
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
This is what i want to happen: If the number is NOT 1 or 2, i want JS to execute this piece of code:
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
Apparently this is not the correct way to write it out, and i've tried writing it a bunch of different ways. Can someone show me the correct way, possibly using the else statement?
if ( value != 1 && value != 2) {
alert("Invalid number. Try again.");
}
If you write value != (1||2), the (1||2) will get first evaluated to 1 and then compared to value, so you effectively wrote:
if ( value != 1 ) { [...] }.
This is because the () have a higher predence than !=. You can also read this explanation about operator predence which gives more details.
1
if ( value != 1 && value !=2 ) {
alert("Invalid number. Try again.");
}
2
if ( !(value == 1 || value ==2) ) {
alert("Invalid number. Try again.");
}
3
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
The best way to write this statement would be as follow:
if ( value == 1 )
{
alert("1");
}
else if ( value == 2 )
{
alert("2");
}
else
{
alert("no 1 or 2");
}
The if statement that you are messing on is (1 || 2)
What will happen is it will do a Boolean test and return 1.
it should look like this
if ( value !== 1 && value !== 2 )
{
alert("no 1 or 2");
}
Thanks
As already noted, the best is to separate into two NOT statements,and evaluate both:
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
However, you could also use the if, else if, else pattern to cover yourself against all other inputs (letters, punctuation, whitespace, etc). The else acts as a catch-all at the end:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
Inline statements like: (1 || 2) only evaluate the right hand side of the || if the left hand side is false-y. So what your statement actually is saying is:
if ( value != 1 )
Because 1 evaluates to true.
As most others have pointed out, what you actually want to do is:
if ( value != 1 && value != 2 )
The logic is incorrect. You have to do in this way
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
the (1||2) statement is evaluated as 1 so you are testing if value != 1
have tried writing
if(value != 1 && value != 2)
You have to do it like
if ( value != 1 && value != 2 ) {
alert("Invalid number. Try again.");
}
OR
if (!(value == 1 || value == 2)) {
alert("Invalid number. Try again.");
}
You can use switch as follows
switch(value) {
case 1:
alert("You have chosen 1.");
break;
case 2:
alert("You have chosen 2.");
break;
default:
alert("Invalid number. Try again.");
}
Your problem is here:
if ( value != (1 || 2) )
What ths is doing is checking if "value" is not equal to (1 OR 2), where (1 OR 2) is evaluated first, because it's in the brackets. (1 OR 2) evaluates to 1, since 1 is truthy in javascript. What your code is actually doing is checking if your value is not equal to 1.
What you actually want to do is check if your value is !=1 and that your value is !=2. You do that like this:
if (value !=1 && value !=2) { /* do something */ }
You don't need a clause. You can just use:
else{
}