RyanUK RyanUK - 1 month ago 15
HTML Question

How to store a value as a string from a text input using javascript

What I'm attempting to do is to save some user input from a html text field into a JS variable and then on a button click place that text into an iframe.

Retrieving the information from the text field using jQuery isn't the issue as I can console log '$('#userinput').val()' which returns the value but then saving it into a variable seems to return an empty string.

This is my code which uses both the jQuery and the vanilla to attempt to store the string:

$(document).ready(function () {

$result = $('#userinput').val();
var output = document.getElementById('userinput').value;
var iframe = document.getElementById('iframe');

doc = iframe.contentDocument;
doc.open();
doc.write("test");
doc.close();

$('#btn_run').click(function () {
console.log($('#userinput').val());
console.log(output);
console.log($result);
doc.open();
doc.write(output);
doc.close();
});
});


And HTML:

<input type="text" id="userinput">
<iframe id="iframe"></iframe>
<button id="btn_run">Run</button>


Confused.

Any help is appreciated :)

Answer

You need to get the value of #userinput in your event listener. This is because strings are a primitive value and are not passed by reference. So when you use .value you are getting the value at the time of the call. When you were in the callback you got the value of an empty string as the input was empty when the value was stored in the output variable.

The snippet won't work here due to the iframe.

$(document).ready(function() {

  $result = $('#userinput').val();
  
  var iframe = document.getElementById('iframe');

  doc = iframe.contentDocument;
  doc.open();
  doc.write("test");
  doc.close();

  $('#btn_run').click(function() {
    console.log($('#userinput').val());
    var output = document.getElementById('userinput').value;
    console.log(output);
    console.log($result);
    doc.open();
    doc.write(output);
    doc.close();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="userinput">

<iframe id="iframe"></iframe>

<button id="btn_run">Run</button>