0

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

2
  • it should be document.getElementById('my-text-box').value Commented Jul 26, 2018 at 19:39
  • Thanks I tried that and still not working; its weird, I used other jsfiddle examples others posted & it does not work for. Almost as if browser settings on my side causing some issue. Commented Jul 26, 2018 at 19:49

4 Answers 4

2

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 ); 
    })
Sign up to request clarification or add additional context in comments.

Comments

2

Your first line:

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

Should be

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

Since value is a property which is not a function, it is a string.

1 Comment

I did have this but still not working but still returning empty string. Thanks for your response.
0

Try this

var textArea = document.getElementById("text");

textArea.addEventListener("change", function() {
    console.log(this.value);
});
<textarea id="text"></textarea>

1 Comment

this works running it here; is there an issue if I am running with jquery (Edge) in order to have console.log work.
0

To take the value of an input, do it this way

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.