Getting empty string or null value from textbox

Tags: ,



I am trying to test a simple <input> item and then print the contents to the console. I have a textbox and will insert some text with then hoping to see the data printed to the console but this is not happening. I am actually trying to test a more complicated item with the <input> being JSON and then reading the fields without knowing what kind of JSON it is or the number of JSON fields.

var input = document.getElementById('my-text-box').value;
var jsonString = JSON.stringify(input);

console.log(document.getElementById('my-text-box').value);

try {
  /*
  message_content = JSON.parse(input);
  
  var message = JSON.parse(input);
  
  for (var key in message) {
    var keyjson = message[key];
    
    if (typeof infoJSON !== "object") {
      console.log(keyjson)
    }
  }
  */
} catch (e) {
  error = true;
  log.error('Something went wrong', e)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="my-text-box"></input>

Here’s a JSFiddle

Answer

First of all Element.value() is not a function, so instead use Element.value this is only valid for input elements.

Second, var input is always assigned an empty string because it was executed before any character enters the input element, to avoid that use the following :

input.addEventListener( 'change', function(){ 
       inputVal = JSON.stringify( this.value ); 
       console.log( inputVal ); 
    })


Source: stackoverflow