Yahia
Yahia

Reputation: 200

Chrome doesn't declare my JavaScript function

There's problem when I test my code on Google Chrome and I don't have any problem when test it on Firefox. I've a function and I call it in onblur event. It's working fine on Firefox but Google Chrome gave me this error on the console

Uncaught ReferenceError: fill is not defined

HTML code:

<input type="text" name="title" id="title" placeholder="mytitle" onblur='fill(this);'>

JavaScript code:

function fill(element,value = false){
    if(element.value == ""){
        $("#"+element.id).css('border-color','red');
    }else{
        $("#"+element.id).css('border-color','#56de56');
    }
    if(value == true){
        if(element.value > 75 || element.value < 5)
            $("#"+element.id).css('border-color','red');
    }
}

and I declared fill function before that line and after that line so I'm facing the same problem.

Upvotes: 3

Views: 111

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

EcmaScript, the standard JS is based on as of version 5.1 does not support optional parameters.

function fill(element,value = false){

Does not do what you expect it to. Instead, you have to do this manually:

function fill(element,value){
     if(typeof value === 'undefined') {
          value = false;
     }

Or in a shorter notion if you're only expecting boolean values

function fill(element,value){
    value = value || false;

Note - These both have cases they miss - as Fabrício Matté suggested in the comments you can also check arguments.length if you want to differenciate not getting an argument passed, and getting undefined explicitly although that's rarely the case.

although optional parameters are in the EcmaScript 6 proposal

(Firefox however, does independently support them even today)

Upvotes: 3

Related Questions