0

I have a form in sidebar on few pages of my website

<form id="test1" name="test1">
 <label for="fname">First Name:</label>
 <input type="text" name="fname" id="fname" />

 <label for="lname">Last Name:</label>
 <input type="text" name="lname" id="lname" />

 <label for="comment">Comment:</label>
 <textarea name="comment" id="comment"><textarea/>

 <input type="submit" />
</form>

My requirement is something odd. If someone has filled up the form (even partially) and then leaving current page (by going to some other page, or closing browser tab/ window), then form should be submitted.

I am putting following jQuery code to achieve following:

<script>
$(window).bind('beforeunload', function(){
    $('form').each(function(index) {
    var filled = false;
    $(this).find("input").each(function() {
        if ($(this).val() != "") {
            filled = true;
        }
    });
    if (filled) { this.submit(); }
});
return confirm('test');
});

Above code is not working properly, form is not getting submitted. Help please.

I-M-JM
  • 15,732
  • 26
  • 77
  • 103

2 Answers2

0

Variable filled is declared inside $(form).each and used outside of it

amtanay
  • 23
  • 5
0
  1. I think you should use $(this) instead of this on submitting.
  2. Maybe you should also check on the value comparison (see e.g. Check if inputs are empty using jQuery)

@amtanay: as far as I can see, the nesting is correct...

New Code (untested):

$(window).bind('beforeunload', function(){
  $('form').each(function(index) {
    var filled = false;
    $(this).find("input").each(function() {
      if ($(this).val() != "") {
        filled = true;
      }
    });
    if (filled) { $(this).submit(); }
  });
  return confirm('test');
});

You could also think about submitting the form as soon as you find a non-empty field. There is no need to check on all the fields, if the form should be submitted even if it is only partially filled up.

Community
  • 1
  • 1
Stefan Neubert
  • 1,053
  • 8
  • 22