First the code:
function searchItems(){
var noParameters = new Boolean(0);
var formFields = $('form')[0].elements;
for(i=0;1<formFields.length;i++){
if(formFields[i].type == 'text'){
if(!(formFields[i].value)){
noParameters = 0;
}
}
}
alert(noParameters.valueOf());
}
This function is called on a form submit. It’s purpose is to see if all form fields of type ‘text’ have no value (empty input boxes).
I do not get an alert when I think I should. The boolean variable is initialized when it is declared, so there is a value in it. The if statements all work as they should, I have checked repeatedly. The only error I have in my browser is “type is null or not an object” which is on the line comparing the form field type to ‘text’.
I have tried different syntax for the alert with no success: noParameters.toString(), assigning noParameters.valueOf() to a variable and then alerting that, ‘true’ and ‘false’ instead of 0 and 1. Why does my alert not show?
You have an infinite loop because the condition
1 < formFields.lengthis always true. Yet,igets increased every time, untilformFields[i]evaluates tonulland you get the exception because you can’t access atypeproperty of a non-object.To your question:
new Boolean(0);creates an absolutely unnecessary Object wrapper for the valuefalse. Don’t use it. Inside the loop, you eventually assign0to the variable. JavaScript is weak-typed so this is syntactically valid, but still odd.Then, in the alert you use the
.valueOf()method. For the number0this will work because it is implicitly converted to aNumberinstance, but uncommon as well. If you’d used just a boolean value, you would not need it.