views:

30

answers:

2

I want to stop a form submit button from reloading a page. This works in Firefox 3.6, Safari 5, and Opera. But Chrome 5 does not prevent the link.

Here is the form.

<form class="container_7" id="find-store-all" action=" ">
 <label for="customer-loc" class="grid_3">Find a Store Near You:</label>
 <input name="customer-loc" id="customer-loc" class="grid_3" type="text" placeholder="zip code or address"  />
    <button type="submit" id="customer-loc-sub" class="grid_1" >Enter</button>
</form>

I am using event delegation to manage the click. Here is the JavaScript.

document.onclick = handleClick;

function handleClick(e){
 if(!e) var e = window.event; 
 var target = e.target || e.srcElement;

 switch(target.id){
  case "customer-loc-sub" :
  e.preventDefault();
  findClosestStoreOne();
  break;
 }

}

Any suggestions would be appreciated.

+2  A: 

preventDefault() isn't the best way to prevent the browser's default behaviour in this type of DOM 0 event handler, as it certainly doesn't work in IE and possibly other browsers too. Just use return false; instead. Works in all browsers.

document.onclick = handleClick;

function handleClick(e){
 if(!e) var e = window.event; 
 var target = e.target || e.srcElement;

 switch(target.id){
  case "customer-loc-sub" :
  findClosestStoreOne();
  return false;
 }
}
Tim Down
Tim, thanks. But return false, doesn't work either. I tried "return false," "e.returnValue = false," and I placed return false in a separate function.
Armando
This works for me in Chrome 5: the form does not submit. Are you sure there's no error in `findClosestStoreOne();`?
Tim Down
Tim, thanks. I found the issue. I had another event that was affecting this. I modified the other event, and both preventDefault() and return false are working now. Thanks for your suggestions. I really appreciate it.
Armando
Ah, ok. Glad you solved it.
Tim Down
A: 

Solved this. There are another event (the entire script is about 900 lines) that was affecting this. Thanks for your help. Especially Ryan Kinal. His comment's got me to look at the problem from another angle...so to speak.

Armando
Always glad to help :-)
Ryan Kinal