Quick javascript help please

Associate
Joined
24 Oct 2002
Posts
980
Location
Manchester
Running into a really weird issue, in my function() block, the if section runs both the true and the else code blocks, what am I doing wrong?

Code:
function StyleAllInputs(){
    var inputs = document.getElementsByTagName('input');
    var texts = document.getElementsByTagName('textarea');
                        
    for (i=0; i<inputs.length; i++) { // loops through the inputs
        //Set the style
        inputs[i].className="default";
        inputs[i].onclick=function() {
            //Build arrays of elements we want to change
            var inputs = document.getElementsByTagName('input');
            var texts = document.getElementsByTagName('textarea');
            //Reset all styles
            for (i=0; i<inputs.length; i++) { // loops through the inputs
                //Set the style
                inputs[i].className="default";
            }
            for (i=0; i<texts.length; i++) { // loops through the inputs
                //Set the style
                texts[i].className="default";
            }
            
            //Then set the current one
            if ((this.readOnly==true) || (this.enabled==false)) {
                this.className="readonly";
            } else {
                this.className="editable";
            }
        }
    }
}

Any tips muchly appreciated. Ta

PS I know it's not finished yet wrt textareas.
 
Are you sure it runs both blocks of the if statement?

Main thing I noticed that was wrong is
Code:
inputs[i].onclick=function()

should be
Code:
inputs[i].onclick=function;

Using the brackets means the result of calling function() is assigned to onclick, not a reference to the function.
 
Cheers for looking, the function bit works as expected as it's an inline function definition.

I'm using the venkman javascript debugger in Firefox and it hits breakpoints on both lines of code. It's very weird.
 
Cheers for looking, the function bit works as expected as it's an inline function definition.

I'm using the venkman javascript debugger in Firefox and it hits breakpoints on both lines of code. It's very weird.

Ah yes I wasn't paying attention sorry!

It's probably trivial but have you tried removing the brackets, i.e.
Code:
if ((this.readOnly==true) || (this.enabled==false))
    this.className="readonly";
else
    this.className="editable";
 
Hmm are you deffinitely sure it's hitting both blocks of the if statement during the same execution of the loop.

Are you stepping through the code or letting it run and hit breakpoints? Because I'm inclined to think that when it enters the else block it is actually the next iteration of the for loop.
 
It appears the error was in the css and the venkman debugger was just being a poo-head making me think both lines were being run, thanks for helping anyway!
 
Back
Top Bottom