How to get div element values in Javascript?

 <html>
 <head>
 <script type="text/javascript">
 function caluculate(x)
  {
 var temp=x+1;
 var cn = document.getElementsByName(temp)[0].childNodes;
 alert( "attribute name :"+cn[0].name + "attributevalue :" + cn[0].nodeValue );  
  }
 </script>
 </head>
 <body>
 <div id="fn1">
  Enter your name: <input type="text" name="name" id="fn" onkeyup="caluculate(this.id)">
  Enter your age:  <input type="text" name="age" id="fa" onkeyup="caluculate(this.id)">
  NAME + AGE :<input type="text" name="nameage" id="fname" value="">
 </div>
 </body> </html>

How to get div element values in Javascript? I want to get the each values of input tag.

Please help me.

Upvotes: 0

Views: 5975

Answers (2)

codeandcloud
codeandcloud

Reputation: 55210

Try something like this.

HTML

<div id="fn1">
    Enter your name: <input type="text" name="name" id="fn" onkeyup="caluculate()">
    Enter your age:  <input type="text" name="age" id="fa" onkeyup="caluculate()">
    NAME + AGE :<input type="text" name="nameage" id="fname" value="">
</div>

JavaScript

function caluculate() {
    var cn = document.getElementById("fn1").getElementsByTagName("input");
    cn[2].value = "name: " + cn[0].value + ", age: " + cn[1].value;
}

Upvotes: 1

Knowledge Craving
Knowledge Craving

Reputation: 7993

Please try the following JavaScript function:-

function caluculate(x)
{
    var ele = document.getElementById(x);
    alert("attribute name: " + ele.name + ", attribute value: " + ele.value);
}

Since this JS function is always being called with the argument being the input element's ID, so there is no need to get / maintain the div element anywhere.

Hope it helps.

Upvotes: 0

Related Questions