user9471385
user9471385

Reputation:

Making a JavaScript form that stores variables then prints them

I need help with this script (i am a complete js newbie) i need the script to store the text that a user types in into a js variable and then print it, this is what i have so far but it doesn't seem to be working:

<div id="body">
  <div id="Form Box">                   
    <form id="frm1" action="/action_page.php">
      Insult: <input type="text" name="fname"><br>
      <input type="button" value="Submit" onclick="forminput();">
    </form>
    <script>
      function othername() {
        var input = document.getElementById("userInput").value;
        alert(input);
      }                 
      print(forminput)
    </script>
  </div>
</div>

Thanks for your help!

Upvotes: 0

Views: 39

Answers (2)

Bj&#246;rn
Bj&#246;rn

Reputation: 67

To get a value from a HTML element the simplest way is to give the HTML element an id.

<input id="textinput" type="text" />
<input id="printbutton" type="button" value="Print">

when a user clicks the button:

// Get the text
var mytext = document.getElementById("textinput").value;

// Get the button
var btn = document.getElementById("printbutton");

// When the user clicks on the button print the text
btn.onclick = function () {
   alert(mytext);
}

To get an output with this text there are several options:

In chrome:

Console.log(mytext);

Get a popup:

alert(mytext);

jsfiddle: https://jsfiddle.net/3ogj1ogs/3/

Upvotes: 0

grammar
grammar

Reputation: 871

There are a couple issues with the script.

  1. The onclick property is saying to call a function named formInput, but that function does not exist. Your script has a function called othername, so you want to use that instead.

  2. The function othername tries to select an element with the id of userInput, but the input in your HTML does not have an id property.

  3. Inside the script tag you are calling a function print which does not exist.

Here is a jsfiddle with your script updated and working: https://jsfiddle.net/grammar/c4yethp5/3/

And here is the updated code

<div id="body">
  <div id="Form Box">
    <form id="frm1" action="/action_page.php">
      Insult: <input type="text" name="fname" id="userInput"><br>
      <input type="button" value="Submit" onclick="othername();"  >
    </form>
    <script>
        function othername() {
          var input = document.getElementById("userInput").value;
          alert(input);
        }
    </script>
  </div>
</div>

Upvotes: 1

Related Questions