this input submit selector with closest form submi

2019-08-12 03:43发布

问题:

I am having a problem with the below code. I am not sure why this selector doesn't work, if I click to submit it doesn't work. Does anybody have any idea what would be proper way without using id or class selector?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    </head>
    <body>
        <script>
        $(this).closest('form').submit(function () {
           alert(1);
           return false;
        });
        </script>
        <form>
          <input type="text" name="example">
          <input type="submit" class="searchBtn">
        </form>
    </body>
</html>

As gdoron were asking me what I am trying to do, I am putting here the entire code, together with Sudhir solution, if anybody else need it. So I am trying to send input values with ajax on submit, but I don't want use class or id selector:

$("input[type='submit']").click(function() {
  $(this).closest('form').submit(function() {
        var values = $(this).serialize();          
        $.ajax({
          type: "POST",
          url: $(this).closest('form').attr('action'),
          data: values,
          success: function(msg){                              
              //saving done
              closeDialog(200);                            
          }           
        });     
        return false;           
  });
});

回答1:

try:

$(document).ready(function() {
  $("input[type='submit']").click(function() {
    $(this).closest('form').submit(function (evt) {
           //evt.preventDefault();
           alert(1);
           return false;
    });
  });
});


回答2:

Change your code:

$(this).closest('form').submit(function () {
           alert(1);
           return false;
        });

To:

$(function(){
    $('form').submit(function () {
        alert(1);
        return false;
    });
}):        

this in your code is the window, no anything inside the <form>.