user6479150
user6479150

Reputation:

Get textbox value in single/multiple

I have a field in my page named as "myField" Now this is dynamic So there are 2 cases i.e. it can be just 1 field as;

<input type="text" name="myField" />

OR there can be 2 fields as below;

<input type="text" name="myField" />
<input type="hidden" name="myField" />

I use the following code to access the value in JS;

document.forms[0].myField[0].value

However, this does not work if there is only 1 field (as in the first case)

How do I write dynamic JS code to handle the same? It should be cross browser compatible.

Upvotes: 0

Views: 136

Answers (2)

Waruna Manjula
Waruna Manjula

Reputation: 3477

document.getElementById("btn").addEventListener("click", function() {
	var texts = document.getElementsByName("n");
    var sum = "";
    for( var i = 0; i < texts.length; i ++ ) {
        sum = sum + texts[i].value;
    }
    document.getElementById("sum").innerHTML = sum;
});
<input type="text" name="n"/>
<input type="text" name="n"/>
<p id="sum"></p>
<button id="btn"> Get Sum</button>

or Visit :How get total sum from input box values using Javascript?

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074148

On first glance of that particular example, it seems odd that those two fields have the same name. Normally one would expect the same name for fields that are mutually-exclusive, or that are the same type and form a list.

But you can still work with them: I wouldn't use the automatic properties, since as you've discovered they're inconsistent (document.forms[0].myField will be the field when there's only one, but a collection of fields with the same name if there's more than one). I'd use querySelectorAll:

var fields = document.querySelectorAll('[name="myField"]');

fields will reliably be a list. You can access the elements of that list using fields[0] and such, and get the length from fields.length.

var fields = document.querySelectorAll('[name="myField"]');
for (var n = 0; n < fields.length; ++n) {
  console.log("fields[" + n + "].value: ", fields[n].value);
}
<input type="text" name="myField" value="the text field"/>
<input type="hidden" name="myField" value="the hidden field"/>

Upvotes: 0

Related Questions