Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - User input through HTML input tag to set a Javascript variable?

I want there to be a textbox on my screen(like the one i'm typing in now) that you can type in then click a submit button and it sends whatever you typed in the box to javascript and javascript prints it out.Here is my code This is the part that works.

<html>
<body>
    <input type="text" id="userInput"=>give me input</input>
    <button onclick="test()">Submit</button>
    <script>
        function test()
        {
            var userInput = document.getElementById("userInput").value;
            document.write(userInput);
        }
    </script>
</body>
</html>

OK so that's nice, but lets say I want input from that textbox and button while I'm already in a function and don't want to restart the function?

Thanks, Jake

like image 863
user1836262 Avatar asked Mar 09 '13 00:03

user1836262


1 Answers

When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:

  • Use var foo = prompt("Give me input");, which will give you the string that the user enters into a popup box (or null if they cancel it)
  • Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.
like image 53
Dennis Avatar answered Oct 12 '22 22:10

Dennis