1

I have a for loop.

In the loop there is an if statement that adds an error css style if the dropdown is found empty.

My problem is that the loop only loops 3 times then stops when it is supposed to loop 15 times.....and i do not know why.

The loop alone works fine, but but when i add the if statement, that's when it becomes weird.

Help.

here is my loop

//add all the id's in an array. array size is 15
var drop_down=["Cars_chassis","Cars_model".....];

for (var i = 0; i < drop_down.length; i++) {
    //check if dropdown is empty
    if(document.getElementById(drop_down[i]).value == ""){

        //change the color of border 
        $('#'+drop_down[i]).css('border-color' , '#dddcdc');
     }
}
1
  • 1
    Can you create a jsfiddle with your example? The loop doesn't seem to have anything odd in it that would cause it to break. Commented Mar 10, 2013 at 17:11

3 Answers 3

3

I would suggest adding a CSS class to each one of these elements instead of specifying their id. Why manage all of those ids when one class can do the trick?

<select id="Cars_chassis" class="bordered-select"></select>
<!-- Add class to other 15 -->

At this point you could statically define a style for these drop downs in CSS.

.bordered-select{
   border-color: #DDDCDC;
}

Or set the style on the elements using the class selector. It appears your using jQuery so the following example would work.

$(".bordered-select").css('border-color', '#DDDCDC');

If you only need to highlight those without a value the following would remove those without a value from the matched set of elements:

$(".bordered-select").filter(function(){
  return $(this).val() == "";
}).css("border-color", "#DDDCDC");

Working Example: http://jsfiddle.net/v4hQz/

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

Comments

0
var drop_down=["Cars_chassis","Cars_model".....];

for (var i = 0; i < drop_down.length; i++) {
    //check if dropdown is empty
    if( $('#' + drop_down[i]).value == ""){

        //change the color of border 
        $('#'+drop_down[i]).css('border-color' , '#dddcdc');
     }
}

OR you can try

var drop_down=["Cars_chassis","Cars_model".....];
var contents = $('#'  + drop_down[i]);
for (var i = 0; i < drop_down.length; i++) {
    //check if dropdown is empty

    if( $(contents[0]).value == ""){

        //change the color of border 
        $('#'+drop_down[i]).css('border-color' , '#dddcdc');
     }
}

Comments

0
document.getElementById(drop_down[i]); //returns a HTML DOM Object

var contents = $('#' + drop_down[i]);  //returns a jQuery Object

You can try replace the if (javascript) to if (jquery syntax)

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.