Stop form from submitting when searching with jQue

2019-08-23 10:44发布

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?

标签: jquery submit
1条回答
干净又极端
2楼-- · 2019-08-23 11:32

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;
  }
查看更多
登录 后发表回答