1

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;           
  });
});
JohnyFree
  • 1,319
  • 3
  • 22
  • 35

2 Answers2

2

try:

$(document).ready(function() {
  $("input[type='submit']").click(function() {
    $(this).closest('form').submit(function (evt) {
           //evt.preventDefault();
           alert(1);
           return false;
    });
  });
});
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • `evt.preventDefault();` is redundant as you `return false` in the end. – gdoron Jun 24 '12 at 06:57
  • 1
    To make the comment complete: http://stackoverflow.com/questions/10729198/what-does-return-false-do/10729215#10729215 – gdoron Jun 24 '12 at 07:01
  • Tnx, this is what I am looking for because I can have situation with more than 1 form. This will work also in such cases. – JohnyFree Jun 24 '12 at 08:20
1

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>.

gdoron
  • 147,333
  • 58
  • 291
  • 367