Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text box value in JavaScript

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"?

like image 942
Gnaniyar Zubair Avatar asked Apr 18 '09 16:04

Gnaniyar Zubair


People also ask

Which method is used to get the textBox value in JS?

The jQuery val() method is to get the form element's value. Here, the form element means the input , textarea , and select elements.

What is text box in JavaScript?

JavaScript TextBox - Modern Text Field with Floating Label. An extended version of the HTML input element that supports both pure-CSS and pure-JavaScript versions. Easily create input groups with icons, buttons, help text, and validation messages.


2 Answers

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"> 
like image 136
Gumbo Avatar answered Sep 23 '22 23:09

Gumbo


+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.

i am getting only "software".

id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:

<input type="text" name="txtJob" value=software engineer> 
like image 30
bobince Avatar answered Sep 25 '22 23:09

bobince