0

I know I can create several types of options, questions, checkboxes, and buttons using in HTML. How can I save the response a user enters and assign it to a variable? Here's the code I'm using right now:

HTML:

<input type="text" value="Hotel Name" id="questionOne"><h1 display="block">WHAT IS THE NAME OF THE HOTEL</h1><br>
<input type="button" value="HELLO" onclick="testFunction()">

JS:

function testFunction() {
    prompt(document.getElementById("questionOne").value;);
}

Shouldn't it activate the function when the HELLO button is clicked, and then it identifies the response through the ID "questionOne" and creates a prompt with the variablev value? I don't understand why it's not working.

I'm new to JS and HTML so please don't go crazy if it's a simple answer. Thank you.

Anh Pham
  • 2,108
  • 9
  • 18
  • 29

2 Answers2

0

Well you can just add event Listener to your input. Like

document.getElementById('questionOne').addEventListener('input',function(){
    var somevariable = prompt(this.value,'');
});

That will save the answer of prompt to 'somevariable'.

chesterkmr
  • 311
  • 2
  • 7
  • I don't want the value of the variable to be the response to the prompt. I want it to be the response to the input. The prompt is merely a way to see if the variable's value changed. – Matthew Kaplan Jul 20 '17 at 22:16
0

I think your problem is to do with where things are defined. Rather than using onclick, add an event listener in your js. e.g.

document.getElementById ("bar").addEventListener ("click", foo);

function foo() {
    prompt(document.getElementById("questionOne").value);
}

and just change the button to have an id and get rid of the onclick:

<input type="button" id="bar" value="HELLO">
andrewf
  • 375
  • 4
  • 10
  • It worked perfectly, thank you! But does that mean the value of the variable questionOne is now whatever I answered the question with? If my answer to the question was "hello" then does variable questionOne == "hello"? – Matthew Kaplan Jul 20 '17 at 22:19
  • You mean you want to set the input questionOne value to whatever they put in the prompt? then do something like: var hotel = prompt(document.getElementById("questionOne").value);document.getElementById("questionOne").value = hotel; – andrewf Jul 20 '17 at 22:47
  • if you are actually trying to get them to enter the hotel name in the text box, and save that value, then in your function you can just have var hotel = documen‌​t.getElementById("qu‌​estionOne").value Just seeing what you commented in the below answer, use alert rather than prompt if you just want to see it so you don't confuse us! Or just console.log() – andrewf Jul 20 '17 at 22:49
  • I figured it out, thank you! And I changed all my prompts to alerts. – Matthew Kaplan Jul 20 '17 at 23:09