Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery, submit form when field loses focus

How can I submit a form when a field (In this case the form only has one field) loses focus?

I tried this, but it's not working:

$("form").submit();

UPDATE

I forgot to mention that the form was created with jquery as well:

$("div").html('<form action="javascript:void(0)" style="display:inline;"><input type="text" value="' + oldValue + '"></form>');

This is probably why it won't submit, I think it's because the events aren't being observed.

like image 240
JP Silvashy Avatar asked Dec 06 '09 23:12

JP Silvashy


People also ask

How to trigger focusout in jQuery?

jQuery focusout() MethodThe focusout() method attaches a function to run when a focusout event occurs on the element, or any elements inside it. Unlike the blur() method, the focusout() method also triggers if any child elements lose focus. Tip: This method is often used together with the focusin() method.

What is the difference between Blur and Focusout?

The focusout event fires when an element has lost focus, after the blur event. The two events differ in that focusout bubbles, while blur does not. The opposite of focusout is the focusin event, which fires when the element has received focus.

How do you remove input field focus?

The blur() method removes focus from an element.

What is onfocusout?

The onfocusout event occurs when an element is about to lose focus. Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you should use the onfocusout event.


3 Answers

$('form :input').blur(function() {
    $(this).closest('form').submit();
});
like image 194
PetersenDidIt Avatar answered Oct 12 '22 03:10

PetersenDidIt


Trigger the form's submit() event when the field loses focus. You can detect this by attaching a blur() event handler to it.

$("#field").blur(function() {
  $("#form").submit();
});

If you field doesn't have an ID or other means of easily identifying it (which I would recommend) you could also do something like this:

$("#form :input").blur(function() {
  $("#form").submit();
});

since there's only one field.

like image 42
cletus Avatar answered Oct 12 '22 05:10

cletus


What about this

var $yourForm = $('#form');

$yourForm.find('input').eq(0).blur(function() {

    $yourForm.submit();
});
like image 24
alex Avatar answered Oct 12 '22 03:10

alex