How to store user input as a variable? - javascript

I am trying to design a simple companion interface for a board game I am creating. How do you request user input, and then update a variable with the new input and display the new result? ie. "What number did you roll?" -> "You are now on [this] space."
Sorry, I am very new to coding... Here is the closest I've got
<var space = 1>
<button onclick="mySpaceNumber()">Die Roll</button>
<p id="demo"></p>
<script>
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll != null) {
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
function mySpace(){
'space'= 'space'+ 'dieroll'
space
}
}
}
</script>

if (dieroll != null) { - This will always be NOT null if something isn't entered. Reason being is that it is UNDEFINED, rather than NULL. These are two different things. Null is an actual value. When a variable has been declared, but no value has been given to it then it becomes undefined.
With that said, I would make this line if (dieroll !== "undefined)"
Regarding 'space'= 'space'+ 'dieroll'
I would not put any apostraphe's in the variable's NAME, that is something you want to do when you declare a string.
Regarding this: You will want to put your code on one line.
From:
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
To:
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
The variable space is undefined, you have not initialized it or given it a value. To do that we need to add this in var space=0;
Lastly, I don't see your HTML so I'm not sure what element the variable space is supposed to reference. If it's some other box or something you can remove the var space=0; and get the value by selecting the element you need it from. Without knowing what that would be or what your html looks like I can't speculate further.
With all that said, here is where we are.
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
function mySpace(){
var space=0;
space = space + dieroll;
return space
}
}
}
Then onto the HTML
This is not valid.
Code Snippet
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("roll").value = dieroll;
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
}
function mySpace(){
result = getSpace();
return result;
}
function getSpace(){
gs1 = +document.getElementById('quantity').value + +document.getElementById('roll').value
return gs1;
}
document.getElementById('quantity').value = +document.getElementById('quantity').value + +document.getElementById('roll').value
}
function resetSpace(){
document.getElementById('quantity').value = '1';
}
<div>Roll:
<input type="number" id="roll" name="roll" style="width: 50px;" />
Current Space:
<input type="number" id="quantity" name="quantity" value="1" style="width: 50px;" />
</div>
<button onclick="mySpaceNumber()">Die Roll</button>
<button id="reset" onclick="resetSpace()">reset</button>
<div id="demo"></div>

Related

Why is my function not returning the alert message?

I'm trying to create a game in which an image of a flag is shown and the user must input the correct name of the flag. I've used a random number generator to generate a flag, with each flag having a value assigned to it as the name. How can I fix my function so it can properly compare the user input to the value for the flag object, and thus alert the user if they are correct or incorrect? New to javascript.
Currently, the index.html has a form wherein the user inputs their guess. This guess has the id of "guess". Then the javascript calls this value and is supposed to compare it to the value associated with the flag object. If they match, it should alert the user "correct", if incorrect it should alert "incorrect". However, with my current script, nothing happens when inputting the answer.
HTML:
<div class="imageContainer">
<script language="javascript">
document.write("<div id = flagImage><img src = " + link[random_num].flag + " alt = Flag width = 250px></div>");
</script>
</div>
<div class="guessEnter">
<form onclick="return false">
<input type="text" id="guess" placeholder="Make a guess...">
<div class="submitButton">
<input type="submit" onclick="checkGuess();">
</div>
</form>
</div>
javascript:
/* Pulls random image to display on page */
random_num = (Math.round((Math.random() * 4) + 1));
link = new Array;
link[1] = { flag: "../assets/flagImages/ad.png", value: 'andorra' };
link[2] = { flag: "../assets/flagImages/ae.png", value: 'uae' + 'united arab emirates' }
link[3] = { flag: "../assets/flagImages/af.png", value: 'afghanistan' };
link[4] = { flag: "../assets/flagImages/ag.png", value: 'antigua and barbuda' };
/* Execute function on enter */
guess.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
checkGuess();
}
});
/* Function that compares user input to link value */
const guess = document.getElementById("guess");
function checkGuess() {
if (link[random_num].value.toLowerCase() === guess.value.toLowerCase()) {
alert('You Win!'); //correct guess
} else {
alert('Wrong!'); //wrong guess
}
}

How to know what type of variable user enter in JavaScript?

I tried to make a function that receive data from user and combine such data either by concatenation in case of string or by getting the sum as a result if the entered data was integer.
My main problem is that I don't know what what condition in if statement I use to JavaScript act according to data entered by user.
That's my last invented code to solve such problem
function GetFullName() {
var first = document.getElementById('FirstName').value;
var last = document.getElementById('LastName').value;
if (first == "string" || last == "string") {
document.getElementById('FullName').value = first + " " + last;
} else {
var first = parseInt(document.getElementById('FirstName').value);
var last = parseInt(document.getElementById('LastName').value);
document.getElementById('FullName').value = first + last;
}
document.getElementById('FirstName').focus();
}
<form>
First Name <input type="text" id="FirstName" />
Last Name <input type="text" id="LastName" />
<input type="button" value="submit" onclick="GetFullName()" />
<input type="reset" value="reset" />
<br />
Full Name <input type="text" id="FullName" />
</form>
when you get an element's value it will always be a string,
you can check of a variables type by typeof first
for your specific problem if you want to check if the user inputted integers then you will have to use isNaN
if(isNaN("123")) {
} else {
//this executes
}
All in all the new code would be:
if (isNaN(first) || isNaN(last)) {
document.getElementById('FullName').value = first + " " + last;
} else {
document.getElementById('FullName').value = parseInt(first) + parseInt(last);
}

Testing if entered value is a number

I had a task to enter a °F and convert it to °C. I also has to show a error messege instead of a number if entered value is not a number. What ever I do I can't get it to work properly. When I type letter it just shows -17.77777777777778 °C instead of messege. Can I get some help from you ?
function temperatura(){
var temp = document.getElementById("tempF").value;
if (isNaN(temp)){
document.getElementById("demo2").innerHTML =
"You need to enter a number!";
} else {
document.getElementById("demo2").innerHTML = uCelzije(temp)+" °C";
}
}
function uCelzije(f){
return (5/9) * ( Number(f) - 32 );
}
<p>Enter Fahrenheit to convert it to Celsius.</p>
<form>
<input type="number" id="tempF">°F
</form>
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p><br>
It's because your input is type of number. If you type a letter, this value is not accepted and it remains an empty string:
isNaN(''); // false
then this empty string is converted to 0 in your uCelzije function:
(5/9) * ( 0 - 32 ); // -17.77777777777778
so you should also check if the input isn't empty, e.g.:
if (temp == '' || isNaN(temp)){
Antonio, if i understood well, maybe you only need to add a new validation to check an empty string, following how you construct your code. Try to add an empty string validation to your script.
var temp = document.getElementById("tempF").value;
if (isNaN(temp) || temp.trim() == ""){
document.getElementById("demo2").innerHTML =
"You need to enter a number!";
} else {
document.getElementById("demo2").innerHTML = uCelzije(temp)+" °C";
}
You need to parse the temp value as int. This will make sure that temp is either a number or NaN. Everything will work just fine.
Edit: This was suggested by #Servuc as well in the question comments.
<p>Enter Fahrenheit to convert it to Celsius.</p>
<form>
<input type="number" id="tempF">°F
</form>
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p>
<br>
<script>
function temperatura() {
var temp = parseInt(document.getElementById("tempF").value);
if (isNaN(temp)) {
document.getElementById("demo2").innerHTML =
"You need to enter a number!";
} else {
document.getElementById("demo2").innerHTML = uCelzije(temp) + " °C";
}
}
function uCelzije(f) {
return (5 / 9) * (Number(f) - 32);
}
</script>

Some issues with JavaScript

I'm passing through some issues while trying to make this code work.
The JavaScript part :
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
function post() {
if (name === "") {
alert("You are missing something :)");
document.getElementById("name").focus();
}
else if (msg === "") {
alert("You are missing something :)");
document.getElementById("msg").focus();
}
else {
document.getElementById("content").innerHTML += ("<p id='post'>Name :. " + name + "</p><br><p id='post'>Comment :. " + msg + "</p><br><p>" + date + "</p>");
alert("Successfully posted :)");
}
}
And the body part :
<div id="content">
<h1>:. Welcome to the discussion .:</h1>
<br><br>
<p>The topic is : The structure of this website.</p>
<br>
Name/Nickname :.<br><input type="text" value="" id="name" maxlenght="32">
<br>
<p>
Message :.<br><textarea id="msg" cols="40" rows="5"></textarea>
<p>
<input type="button" value="Post" onClick="javascript:post()">
</div>
I get some issues when I press the 'post' button, it shows up the alert even being with or without letters on the 'name' and 'msg' inputs. And I can't see if the 'else' part will work because I can't even pass through the first part :c . I tried everything, but no success, hope someone can give me a light.
This section only gets run once:
var name = document.getElementById("name").value ;
var msg = document.getElementById("msg").value ;
var date = new Date();
If you want to recheck the name value when post is called, you should have name be reassigned to document.getElementById("name").value within the post function.

Get variable via user input

I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});

Categories

Resources