Stop form from submitting when searching with jQue

2019-08-23 11:05发布

问题:

I have a google map search input on my form. If the user types an address and hits enter, the entire form is submitted rather than searching the map. I'm using the code below to prevent this:

jQuery('#gform_6').submit(function() {
    // check if address field is empty or not
   if(jQuery("#map_search").val()=="") // empty
      return true; // ok submit form
   else { // address filled
      ChangeMap();
      jQuery("#map_search").val("");
      return false;
    }
});

However, I can use this feature one time. If I try to search again and hit enter, nothing happens. Is it because I'm returning "false" on the submit function?

回答1:

I believe you're looking for event.preventDefault()

event.preventDefault : If this method is called, the default action of the event will not be triggered.

jQuery('#gform_6').submit(function(event) {
  event.preventDefault();
  // check if address field is empty or not
  if(jQuery("#map_search").val()==""){ // empty
     return true; // ok submit form
  }else { // address filled
    ChangeMap();
    jQuery("#map_search").val("");
    return false;
  }


标签: jquery submit