How to get numeric value from a prompt box?
parseInt() or parseFloat() are functions in JavaScript which can help you convert the values into integers or floats respectively.
Syntax:
parseInt(string, radix);
parseFloat(string);
- string: the string expression to be parsed as a number.
- radix: (optional, but highly encouraged) the base of the numeral system to be used - a number between 2 and 36.
Example:
var x = prompt("Enter a Value", "0");
var y = prompt("Enter a Value", "0");
var num1 = parseInt(x);
var num2 = parseInt(y);
After this you can perform which ever calculations you want on them.
Input as number in JavaScript prompt
No you can't customize the built-in browser prompt for security reasons.
Your best bet is to use a JavaScript library which offers such a feature like SweetAlert
You can create a number prompt like this:
swal({
input: 'number',
title: 'Enter a number',
}).then(function(result){
alert("You picked number " + result.value);
});
Alternatively you could verify the user's input yourself and stick with prompt like this:
// need a way to check if input is a valid number
var isNumber = Number.isInteger || function(number){ return !isNaN(parseFloat(n)) && isFinite(n) }
var result = prompt("Enter your number");
if (!isNumber(result)){
prompt("Please try again and enter your number");
}
I would strongly advice against using prompts as the user's browser will most likely block too many prompts in a row. Also keep in mind that the native prompt will block every other interaction a user can make with your side, you don't receive events and your UI won't update. Your website basically freezes until a user interacts with said prompt/alert/confirm.
Window.prompt accept only numeric values
You should reduce your code to the minimum required to reproduce the issue, e.g.:
var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);
if (selection != (/^[0-9.,]+$/)){ console.log('fail');} else { console.log('pass');}
ReactJS: How To Get Input Value From The Prompt Box And Update It To Database
React this.setState
, and useState
does not make changes directly to the state object.
React this.setState
, and React.useState
create queues for React core to update the state object of a React component.
So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.
Try below code that's works !
function FoodListTable(props) {
/* Definition of handleClick in component */
const [newFoodName, setNewFoodName] = useState("");
const handleEdit = () => {
const enteredFood = prompt('Please enter your new food:');
setNewFoodName(enteredFood);
if (enteredFood) {
Axios.put("https://mern-lefood.herokuapp.com/update", {
newFoodName: enteredFood,
id: props.val._id
})
}
}
return (
<button onClick={handleEdit}>Edit</button>
)
}
For more detail Click here
How to get a number to display in alert box rather than NAN
First take a value then perform every logic:
var feetMark = prompt('How tall is mark in feet?');
var lbsMark = prompt('How much does mark weigh in pounds?');
feetMark = parseFloat(feetMark);
lbsMark = parseFloat(lbsMark);
var kgMark = lbsMark / 2.2046;
var meterMark = feetMark / 3.2808;
var bmiMark = kgMark / (meterMark * meterMark);
alert('Mark is ' + ' ' + kgMark + ' '+ 'kilograms');
alert('Mark is ' + ' ' + meterMark + ' ' + 'meters');
alert('Marks BMI is ' + ' ' + bmiMark);
specify the variable type in the prompt
prompt
is extremely basic and offers no way to constrain the input other than the way browsers do by default (e.g., no line breaks).
Instead, convert the string to number afterward. There are a lot of ways to do that:
- Unary
+
:var jonage = +prompt("enter the johns age");
Number
:var jonage = Number(prompt("enter the johns age"));
parseInt
:var jonage = parseInt(prompt("enter the johns age"));
parseFloat
:var jonage = parseFloat(prompt("enter the johns age"));
Unary +
and Number
:
...work the same way:
- They convert the entire string to number if possible, yielding
NaN
if the entire string can't be converted to number. So+"123abc"
isNaN
. - They convert an empty string (
""
) to0
(surprisingly). - They respect JavaScript syntax for specifying the number base (radix), so
+"0x10"
is 16 and+"0o10"
is8
.
parseInt
- Converts only as much of the string as it can before the first invalid character, not the whole string. So
parstInt("123abc")
is123
. - Converts an empty string (
""
) toNaN
(not0
). - Respects JavaScript syntax for specifying the number base (radix), e.g.,
parseInt("0x10")
is 16. - Also lets you specify the radix explicitly as a second argument, to force it to treat the input as being in that number base:
parseInt("0x10", 10)
is0
(because thex
becomes invalid,0x
is no longer treated as indicating the number base. This used to be important with decimal in case end users entered strings like"010"
and browsers implemented "legacy" Octal (leading0
instead of leading0o
), but it's been eight years now (since the 5th edition spec) sinceparseInt
was officially not allowed to do that. - As the name suggests, only converts the part of the string that defines a whole number (integer).
parseFloat
Like parseInt
, but does fractional numbers and doesn't do radix prefixes. parseFloat("0x16")
is 0
, because the x
is invalid (because it doesn't do radix prefixes).
Related Topics
Difference Between Client-Side and Server-side Programming
Download File Using an Ajax Request
How to Call PHP Functions by JavaScript
Execute PHP Function With Onclick
JavaScript Does Not Fire After Appending
"Mixed Content Blocked" When Running an Http Ajax Operation in an Https Page
Pass JavaScript Variable to PHP Via Ajax
Encrypt With PHP, Decrypt With JavaScript (Cryptojs)
How to Refresh Page on Back Button Click
Determine Timezone from Latitude/Longitude Without Using Web Services Like Geonames.Org
Displaying Pdf from Arraybuffer
Do Dom Tree Elements With Ids Become Global Properties
How to Change an Element'S Class With JavaScript
Can Scripts Be Inserted With Innerhtml
Which "Href" Value Should I Use For JavaScript Links, "#" or "JavaScript:Void(0)"
Adding Two Numbers Concatenates Them Instead of Calculating the Sum
Why Don't Self-Closing Script Elements Work
Persisting the Changes of Range Objects After Selection in Html