1

i have a form with name frmOrderReschedule and an hidden element frmOrderReschedule. i tried to access it in this way-

document.frmOrderReschedule.newSalesOrderNumber.length

it gave me error document.frmOrderReschedule.newSalesOrderNumber.length is undefined, but when i try in fallowing way it works properly

document.getElementsByName('newSalesOrderNumber').length;  

this is happening in Mozila only.Any one can throw some light on it, why it's happenning like this. Thanks in Advance!!!

4
  • 1
    What does document.frmOrderReschedule.newSalesOrderNumber return? What kind of element is newSalesOrderNumber? How many are there actually? Can you show the HTML? BTW, you should avoid DOM 0 access of form elements as in your first example. document.forms["frmOrderReschedule"].elements["newSalesOrderNumber"]is better and more readable. Commented Jun 14, 2011 at 9:40
  • document.frmOrderReschedule.newSalesOrderNumber is hidden element,it can be multiple depending upon requirement Commented Jun 14, 2011 at 9:43
  • i have only one form in my page that's why i have used first example Commented Jun 14, 2011 at 9:45
  • If you have only one input with this name, just give it ID and use document.getElementById("newSalesOrderNumber") instead - this is most efficient way. To check the length of the value use document.getElementById("newSalesOrderNumber").value.length. Commented Jun 14, 2011 at 10:25

1 Answer 1

2

Following your comment I deduct, that the field can be present one or multiple times. In that case document.frmOrderReschedule.newSalesOrderNumber (or document.forms["frmOrderReschedule"].elements["newSalesOrderNumber"]) can return different types.

If there are multiple controls, it will return a collection, which will have a length property. If there is only one control, then it will return a direct reference to that control, which - obviously - doesn't have a length. That means, if you use that syntax you need to distinguish between the two variants (or even three variant, in case the field isn't there):

var x = document.forms["frmOrderReschedule"].elements["newSalesOrderNumber"];
if (x) {
    if (x.length) {
        alert("There are " + x.length + " controls.")
    } else {
        alert("One control with value: " + x.value);
    }
} else {
    alert("None");
}

Working example: http://jsfiddle.net/H4Lks/1/

document.getElementsByName('newSalesOrderNumber') on the other hand always returns a collection, even if there are none or one, so it always has a length.

Sign up to request clarification or add additional context in comments.

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.