1

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.

1

4 Answers 4

2

Yes, because in the first case you should use document.forms[0].myField.value.

I'd suggest to retrieve elements with getElementsByName() method:

var val = document.getElementsByName("myField")[0].value;
Sign up to request clarification or add additional context in comments.

2 Comments

is this cross browser compatible ?
@testndtv Of course. This is a native JavaScript method for DOM manipulation.
0

better way is to give a unique ID to each element and then get it with

document.getElementById(id).value

Comments

0

Have a look at JQuery, and here's some information on how to get the value out.

Comments

0

provided there is at least one element name "myField"

var count = document.forms[0].myField.length;
for(var i=0; i < count; i++){
    // do something with document.forms[0].myField[i].value
    console.log(document.forms[0].myField[i].value);
}

fiddle : http://jsfiddle.net/HtrrT/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.