user94
user94

Reputation: 25

how to access contents of a text box using name of the input text box element in javascript?

  function display() {
    var x = document.nid.value;
    //document.body.innerHTML=x;
    document.write(x);
  }
<head>
  <meta charset="ISO-8859-1">
  <title>Print Reverse of a number</title>
</head>

<body>
  <table>
    <tr>
      <td>
        Enter number
      </td>
      <td>
        <input type="number" size="20" name="nid">
      </td>
    </tr>
    <tr>
      <td align="center" colspan="2">
        <input type="submit" value="submit" onclick="display()">
      </td>
    </tr>
  </table>
</body>

Upvotes: 0

Views: 598

Answers (4)

Gowtham
Gowtham

Reputation: 1597

var inputField=document.getElementsByName('nid');

This Will return you array of 0th element, then you can get the value

var inputValue=inputField[0].value;

(Or you can directly make it in a single variable)

var inputFieldValue=document.getElementsByName('nid')[0].value;

Upvotes: 0

niyasc
niyasc

Reputation: 4490

You can use document.getElementsByName(name) to select all nodes by name. It will return an array, take the node for which you want to retrieve value and use value method.

function logValue() {
  console.log(document.getElementsByName("nid")[0].value);
}
<input type="number" size="20" name="nid" onchange="logValue()">

Upvotes: 0

Syam Pillai
Syam Pillai

Reputation: 5217

var yourinputs = document.getElementByName("nid")

this will return an array of elements. Since you need the first one, you can choose the 0th element of array

var input_val = yourinputs[0].value;

or simply in one line as

var input_val = document.getElementByName("nid")[0].value;

Upvotes: 0

Weedoze
Weedoze

Reputation: 13943

Your should replace

var x = document.nid.value

By

x = document.getElementsByName("nid")[0].value;

Upvotes: 4

Related Questions