codeGeass codeGeass - 3 months ago 14
jQuery Question

How to make a jQuery event only once?

When I click on "DELETE", the function

deleting()
is called. How can I prepend only once, even if I click on DELETE many times? I want it to happen just the first time I click.



function deleting() {
$(".checking").prepend("<input type='checkbox' name='idcheckbox'>");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:deleting()">DELETE</a>
<div class="checking"></div>




Answer

You may use jQuery one in order to: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

You may attach the event dynamically and not inline:

    $(function () {
        $('a').one('click', function(e) {
            e.preventDefault();
            $(".checking").prepend("<input type='checkbox' name='idcheckbox'>");
        })
    });

And you html could be like:

<form>
 <a href="">DELETE</a>
</form>
Comments