How to get text box value in JavaScript

Gnaniyar Zubair picture Gnaniyar Zubair · Apr 18, 2009 · Viewed 751.9k times · Source

I am trying to use JavaScript to get the value from an HTML text box but value is not coming after white space

For example:

<input type="text" name="txtJob" value="software engineer">

I only get: "software" from the above. I am using a script like this:

var jobValue = document.getElementById('txtJob').value

How do I get the full value: "software engineer"?

Answer

Gumbo picture Gumbo · Apr 18, 2009

Your element does not have an ID but just a name. So you could either use getElementsByName() method to get a list of all elements with this name:

var jobValue = document.getElementsByName('txtJob')[0].value  // first element in DOM  (index 0) with name="txtJob"

Or you assign an ID to the element:

<input type="text" name="txtJob" id="txtJob" value="software engineer">