Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中获取文本框值(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

(我正在尝试使用JavaScript从HTML文本框中获取值,但值不是在空格之后)

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

(我如何获得全部价值:“软件工程师”?)

  ask by Gnaniyar Zubair translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your element does not have an ID but just a name.

(您的元素没有ID,只有一个名称。)

So you could either use getElementsByName() method to get a list of all elements with this name:

(因此,您可以使用getElementsByName()方法获取具有此名称的所有元素的列表:)

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

Or you assign an ID to the element:

(或者您为元素分配ID:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...