1

I have piece of JavaScript code which cycles through form elements and builds an object. I have a mixture of HTML input fields and ASP.NET input fields. ASP.NET changes the ID of the fields to the form xxxxx_yyyy_id, so I am attempting to use the split function to extract the original id.

 // Iterate over all the text fields and build an object
 $(':text').each(function () {

     var tokens = this.id.split("_");
     if (tokens.length = 3) {
         // Assume this is a .net inputbox - extract the original id
         inFormData[tokens[2]] = this.value;
     } else {             
         inFormData[this.id] = this.value;
     }
 });

Stepping through the above code, the first id is ctl00_ContentPlaceHolderCol1_forenameField, so the tokens.length = 3 code is run. On the second iteration, the id is forenameField2 so I would expect the tokens.length to be 1, but it is actually 3. The else statement is never run.

This could be something simple, but I cant work it out. If I inspect the tokens array it has only 1 element in on the second iteration. I have also tried setting the array.length to 0 after each iteration.

Any help appreciated.

1
  • = is assignment - you mean == (or even better ===) Commented Apr 30, 2012 at 16:14

4 Answers 4

4

Correct this:

== instead of =. === is more better


     if (tokens.length == 3) {
         // Assume this is a .net inputbox - extract the original id
         inFormData[tokens[2]] = this.value;
     } else {             
         inFormData[this.id] = this.value;
     }
Sign up to request clarification or add additional context in comments.

1 Comment

Some people advice to use the constant at the left (3 == tokens.length), because if you forget a = it becomes a compilation error. I don't like it, but it's got a point.
2

Change your = 3 to === 3

At the moment you're overwriting tokens.length every time.

NB: === is preferred to == because it's an exact equality check. The two-equals version will attempt to cast the two operands to the same type before comparison, which is 1. unnecessary, 2. inefficient, 3. sometimes error prone.

Comments

2

That is why you should always put the constant first when testing. If you forget a comparison sign it will throw an error:

if( 3 = tokens.length ) // throws an error
if( 3 == tokens.length ) // ok
if( 3 === tokens.length) // ok

Comments

1

from:

if (tokens.length = 3) {

to:

if (tokens.length == 3) {

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.