0

I have a HTML page with an input field
Someone enters some text into it
They click a button

I want to grab the value of the input field AFTER they click the button with some JS code(client-side) and then print it to the console/save it to a file.

How would I go about doing this? I've tried looking but I can't find anything like this at all :/

Thanks! :)

qwerghjk
  • 5
  • 3
  • 3
    Possible duplicate of [How can I listen to the form submit event in javascript?](https://stackoverflow.com/questions/7410063/how-can-i-listen-to-the-form-submit-event-in-javascript) – Isaac Jul 20 '18 at 00:36
  • You can't save it to a file client side if they're in a browser, but if you're using node import `fs` – Andria Jul 20 '18 at 00:51
  • @chbchb55 Incorrect. You can save text input to a file using javascript. Here is a simple example [**JsFiddle Demo**](https://jsfiddle.net/9yd62eum/) – NewToJS Jul 20 '18 at 00:57
  • @NewToJS, strictly programmatically speaking you can't, however, if you want the visitor to download the file that is possible – Andria Jul 20 '18 at 01:00
  • @chbchb55 Maybe this depends if *"save it to a file"* means a file on the server or allow the client to save it to file on their computer via download. – NewToJS Jul 20 '18 at 01:04

2 Answers2

1

This example should help you to achieve your goals.

const inputNode = document.getElementById('input');
const buttonNode = document.getElementById('button');

buttonNode.addEventListener('click', () => {
  const inputValue = inputNode.value;
  
  // do what ever you wan't
});
<input id="input" type="text" />
<button id="button">Click</button>
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
  • Er, this isn't working :P I put `document.write("hi)` in place of the commented out code, but nothing comes :/ – qwerghjk Jul 20 '18 at 01:33
  • I placed the script src at the start of the body in the .html file lol @benvc Thanks Roman! – qwerghjk Jul 20 '18 at 06:28
1

Try this:

// This function is called by the HTML code onclick on the button
var get_content_of_input = function(){
    var user_input = document.getElementById("text_field").value;
    // Now you can use the variable user_input containing the text
}
<input id="text_field">Please enter Text</input>
<button id="button" onclick="get_content_of_input()">Click here to sumbit</button>

The content of the text field will now be saved in the variable "user_input".

Lvn Rtg
  • 54
  • 6