简体   繁体   中英

JavaScript get the value of input in a div

I want to get the value of an input in a div. I've tried document.getElementById('id').getElementsByTagName('input') but somehow I can't get the value.

HTML:

<div id="ST_RTM1_352X-MESSAGE_TYPED01_TXT">
    <input class="MobileEditDisabled ABLED" value="E" size="2" maxlength="2" type="text">
</div>

JS :

var getV = document.getElementById("ST_RTM1_352X-MESSAGE_TYPED01_TXT").getElementsByTagName('input');
alert(getV.value);

JSFiddle: http://jsfiddle.net/aldimeola1122/2aLn33hn/

Or be more clever:

var getV = document.querySelector("#ST_RTM1_352X-MESSAGE_TYPED01_TXT input");
alert(getV.value);

getV contains a collection of nodes. You need to get first element getV[0] or getV.item(0) and then do another operations.

.getElementsByTagName返回一个集合-引用所需的索引:

var getV = document.getElementById("ST_RTM1_352X-MESSAGE_TYPED01_TXT").getElementsByTagName('input')[0];

You forgot de position because getV will get a collention's nodes, use [0] to get the node:

var getV = document.getElementById("ST_RTM1_352X-MESSAGE_TYPED01_TXT").getElementsByTagName('input')[0];

DEMO LIVE

只需在getElementsByTagName('input')之后添加[0]

A Solution...

Lets say it like this: My Version takes the Div Element and searches for All Input child Elements. It works ;)

var getV = document.getElementById("ST_RTM1_352X-
MESSAGE_TYPED01_TXT").getElementsByTagName('input');
alert("Inputelements in the Div:" +getV.length);
for (var i = 0; i<getV.length; i++){
    alert("Value of input " + i + ": " + getV[i].value);   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM