I need to create a code in HTML/Javascript that will allow a user to enter an answer to a maths question and then the site needs to validate whether that answer is correct.
Been playing around for a few hours and researched the web but not found anything close.
Any help is appreciated!!
You could use javascript for validation,
Look at this example.
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
checking if value of a textfield is integer in javascript
Javascript validation
function isInteger(number) {
var getVal = parseInt(number);
if (number.length == 0 || getVal == Number.NaN || getVal <= 0) {
return false;
}
return true;
}
Related
I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.
I'm having trouble getting the Codecademy section of ifNan done. How do I make it so the ifNan function checks the number I manually input at the end when I run the function. For example:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (isNan(number)) {
return "Your input is not a number!";
} else {
return false;
}
};
isEven(2);
What would I put in the isNan function so that when I input the number at the bottom it also checks if it is actually a number?
you could condense that down to:
function isEven(number)
{
if(!isNaN(number) || number % 2 === 0)
{
return true;
}
return false;
}
See elclanrs comment. isNan is not a function isNaN is. caps matter there.
So...update to this long-standing issue:
I went back to codecademy and restarted the lesson. After researching for about a week, and a good long breather, I came back to this frustrating issue and even then found myself writing the same exact code that I had in the beginning of this issue (because I knew it was correct).
You all made valid points.
Dennis you're absolutely right this can be condensed in a few areas but Codecademy is very rigid (which I'm liking less and less) so it would have never let me pass the dang section.
Anyways, I wanted to close this but "answer" (kind of) it first.
Thanks for all your assistance.
Try this:
var isEven = function(number) { if (number % 2 === 0) { return true; } else if(isNaN(number) === true || false){ return "your input is not a number"; } else { return false; }// Your code goes here!
}; isEven("Gbemi")
I have a form, and on the form I have an input box that can hold the value of an integer. When the user submits this form, it needs to first check in jQuery if the value of the input box is numeric as well as checking if it is in increments of 100.
So, if the user submits "hello" it will give an error. If the user types "1099" it will give an error. If the user types "1000" or "1100" it will give success.
Any ideas how to do this?
if(/^(\d*0|)0$/.test($('#inputId').val())){
// numeric and multiple of 100
}
JSFiddle
Check the value of the input when you submit the form (or on an event such as keyup or change maybe), then validate with this function:
function isMultipleOf100(num) {
return !isNaN(num) && num % 100 === 0;
}
Try something like this:
var x = $('input#myInput').val();
if(!isNaN(x)) {
if(x % 100 === 0) {
//valid
}
}
You can use a combination of a regex and a modulus check...
check = 1000;
var intRegex = /^\d+$/;
if (intRegex.test(check)) {
if (check % 100 === 0) {
alert('Pass');
} else {
alert('Fail');
}
}
I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":
function checkforNumber()
{
if (isNaN(sInput || dInput || pInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
Am I using this function incorrectly? Is there something wrong with the syntax?
Thanks
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please reset the form.");
}
also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.
var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))
This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.
I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")