user866190
user866190

Reputation: 863

Understanding Javascript Form Onsubmit

Trying to cancel the sending of an empty form. Confused as there seems to be no reason why this doesnt work. Using firefox as my browser.

Could anybody explain why this code does not cancel the form being sent yet it fires the alert dialog.

addEvent(searchForm, "onsubmit", function(){
    if(inputBox.value.trim() === ""){
        alert("empty"); //this line gets called
        return false;   //this doesn't 
    }
});

Many Thanks

this is the addEvent function

function addEvent(element, listener, func){   

    if(element.addEventListener){

        listener = listener.substr(2, listener.length);
       element.addEventListener(listener, func);

    } else {

        element.attachListener(listener, func);

}

}

Upvotes: 0

Views: 129

Answers (2)

Hemant_Negi
Hemant_Negi

Reputation: 2078

addEvent is not a native javascript function.

use this instead..

    searchForm.onsubmit =  function(e){
        if(inputBox.value.trim() === ""){
             alert("empty");
             e.preventDefault();
             return false;
        }
    }

Upvotes: 1

Joe Minichino
Joe Minichino

Reputation: 2773

your handler should be

function(e){
  if(inputBox.value.trim() == ""){
   alert('empty');
   e.preventDefault();
  }
}

Normally regardless of the framework used handlers support passing the event itself as an argument.

Upvotes: 1

Related Questions