简体   繁体   中英

How can I make a form within a tooltip?

I want to use jQuery to make a form that has a simple yes or no that shows up when you hover over it. The problem is I can't seem to get jQuery to acknowledge the creation of the tooltip as it is dynamically created (eg "$('#word_form').size() = 0") and the submit alert doesn't run. I tested the form alone and it was working. Here is the code:

HTML:

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<p>
Example 1 : <a href="#" class = "word">Cat</a>
Example 2 : <a href="#" class = "word">Dog</a>
</p>

Javascript:

$( document ).ready( function() {
    $(".word").tooltip({
        items: '.word',
        content: '
        <div class="tooltip">Is this word cool?<br> \
            <form id = "word_form" method="POST"> \
                <input type="image" src="http://upload.wikimedia.org/wikipedia/commons/8/87/Symbol_thumbs_up.svg" style="width:50px;height:50px;"> \
                <input type="image" src="http://upload.wikimedia.org/wikipedia/commons/8/84/Symbol_thumbs_down.svg" style="width:50px;height:50px;"> \
            </form> \
        </div>',
        hide: {
            delay: 1000
        }
    });
    $('#word_form').submit(function() {
        alert("Why is this not popping up?");
    });
});

See the Fiddle .

Is using a jQuery tooltip form even possible? If so, what am I doing wrong if not, what might be an alernative? Thanks!

Basically jQuery UI tooltip HTML is not created until the tooltip is revealed so the submit event you are trying to bind is not firing because it is not attached to anything.

To bind events to elements that are created on the fly use '.on()' method. So your on submit event should look like that

$("body").on("submit", "#word_form", function() {
        alert("Why is this not popping up?");
    });

You should set an open callback in your tooltip declaration. There are events that are triggered by the jQuery UI tooltip function. So you can pass a function to the options that will be executed when the tooltip opens.

$(".word").tooltip({
    items: '.word',
    ...
    open: function( event, ui ) {
        $('#word_form').submit(function() {
            alert("This *will* pop up!");
        });
    }
});

You can set any bindings at that point, so it'll actually bind on submit, because the form will exist once that event is triggered.

The bonus of doing it this way is that the binding is only set when a tooltip is active, so you won't have an extra binding on the body tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM