+ 1

JavaScript User Input [SOLVED]

This might seem like a stupid question, but I'm talking about parameters different from strings. I know you can use prompt() to get a string-type value, but how can you get other values from the user? Such as integer or float?

31st Dec 2021, 4:09 PM
Billy Beagle
13 Answers
+ 7
Billy Beagle Just convert user Input to number Number(input)
31st Dec 2021, 4:41 PM
Pariket Thakur
Pariket Thakur - avatar
+ 3
Billy Beagle, For better understanding of what the problem is, it is recommended of you to attach a link to the code in the thread's Description above, so that people can review 👍
1st Jan 2022, 6:44 AM
Ipang
+ 2
I don't think you can. A solution would be: var user = prompt("your age: ") while(typeof(user) != number){ user = prompt("Please enter your age:"); } So basically, you force the user to input a number to stop showing the prompt.
31st Dec 2021, 4:18 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 2
Pariket Thakur that s not a complete solution. If he asks for a number but the user inputs something random just to get rid of the prompt, you will expect a number and not get one, so there may be a lot of issues wherever you use that variable.
31st Dec 2021, 4:43 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
+ 1
🍇 Alex Tușinean 💜 For that he can use if statement
31st Dec 2021, 4:49 PM
Pariket Thakur
Pariket Thakur - avatar
+ 1
When you say prompt() it returns a string by default. You must cast the value to a number type and you can either use: Number(prompt()) or parseInt(prompt()). Strings see '+' as concatenating operator. And the string with just numeric values are implicitly converted to numbers and the operation is performed on them. Hope this helps?
1st Jan 2022, 3:01 PM
R£∆L ∆LILI
R£∆L ∆LILI - avatar
+ 1
As Ipang said, you should attach a link to the code or post the code here in Q&A so that we can review it for easy understanding. Maybe there is another mistake that you are not aware of it.
1st Jan 2022, 4:06 PM
R£∆L ∆LILI
R£∆L ∆LILI - avatar
+ 1
Nevermind, someone answered my question in the code's comment.
1st Jan 2022, 5:25 PM
Billy Beagle
+ 1
I think the simplest way to do that is: var x = Number(prompt("Enter a number:")); var y = x + 3; document.write(y);
1st Jan 2022, 6:56 PM
R£∆L ∆LILI
R£∆L ∆LILI - avatar
0
Pariket Thakur For some reason the Number() method doesnt work. The variable is still string type. I also tried parseInt(), same thing
31st Dec 2021, 5:27 PM
Billy Beagle
0
R£∆L ∆LILI I tried converting the variable but it does nothing. It remains string-type
1st Jan 2022, 3:23 PM
Billy Beagle