Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate events for subelements including the current element

Tags:

html

jquery

I want to make a general jQuery code which will catch all the submit events of <form> subelements including the container element (in case it's a form).

The cases are:

The container is a form

<form>
    <button>hi</button>
</form>

The container is another element containing forms

<div>
    <form>
        <button>submit</button>
    </form>
</div>

What's the cleanest code to do this?

My current solution is the following:

function submit(e) {
   // do something
}

$(containerSelectorOrjQueryObject).on("submit", "form", submit);
$(containerSelectorOrjQueryObject).on("submit", submit);

However, I'd be happy to know if there is a better solution, using just one on call.

like image 850
Ionică Bizău Avatar asked Nov 09 '22 16:11

Ionică Bizău


1 Answers

You can use a class attribute for this as a way to set up a delegate to catch the submit event of any child form no matter what the parent element is. Because it is a delegate, this will also catch anything fired by elements that have been dynamically added as well.

Example that includes a single form scenario, multiple forms in div scenario, and a button to add a form dynamically:

var alreadyAdded;

function submit(e) {
    // do something
    alert(e.target.name);
    return false;
}

$("body").on("submit", ".outerContainer", submit);

$("#addAnotherDynamically").on("click", function(e) {
    if (typeof(alreadyAdded) === "undefined") {
        alreadyAdded = true;
        $("#test2").append("<form name='form4'><button>submit 4</button></form>");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
    <form id="test1" name="form1" class="outerContainer">
        <button>submit 1</button>
    </form>
    
    <div id="test2" class="outerContainer">
        <form name="form2">
            <button>submit 2</button>
        </form>
        <form name="form3">
            <button>submit 3</button>
        </form>        
    </div>
    
    <br>
    <button id="addAnotherDynamically">Add another form</button>
</body>
like image 150
Brian Swift Avatar answered Nov 15 '22 10:11

Brian Swift