How can I make a form within a tooltip? - javascript

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 (e.g. "$('#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 : Cat
Example 2 : Dog
</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.

Related

Refresh javascript's function without using Recursion

I'm trying to create a simple form where i can add more text field after current text field.
And also i can add more field from the new field that ive added before (im using Recursion for this).
Problems come when i click the add on the first field, it creates more then 1 new fields (this happens because of recursion)
how do i refresh javascripts function without calling it again and again?
HTML :
<div class="line-input">
<input type='text' class='ipt-txt'>
<input type='submit' class='btn-smt' value="add new">
</div>
JS :
$(document).ready(function(){
callFunction();
});
function callFunction(){
$(".btn-smt").click(function(e){
$(this).parent(".line-input").clone().insertAfter($(this).parent(".line-input"));
callFunction();
});
};
JSFiddle : https://jsfiddle.net/1uofya3k/
Thanks!
Use event delegation:
$(function() {
$(document).on("click", ".btn-smt", function(e) {
$(this).parent(".line-input").clone().insertAfter($(this).parent(".line-input"));
});
});
That sets up an event handler at the document level that responds to clicks on your button class. You only have to add it once, and it'll work for all subsequent elements that are added dynamically.
(You don't really even have to do it in a "ready" handler; you can set it up before the DOM has been completed.)
Add true to the clone() function. From the jQuery API:
withDataAndEvents (default: false) Type: Boolean A Boolean indicating
whether event handlers should be copied along with the elements. As of
jQuery 1.4, element data will be copied as well.
https://api.jquery.com/clone/
$(document).ready(function() {
callFunction();
});
function callFunction() {
$(".btn-smt").click(function(e) {
e.stopPropagation();
$(this).parent(".line-input").clone(true).insertAfter($(this).parent(".line-input"));
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="line-input">
<input type='text' class='ipt-txt'>
<input type='submit' class='btn-smt' value="add new">
</div>

Add click event to dynamically added button to kendo window content

I have kendo window and im adding content dynamically to kendo window.
The content has a button and i wanted to attach click event to that button.
jQuery is able to find the button from the content, attach click event however click event never gets fired
JSFiddle
Html
<div id="example">
<div id="window">
</div>
</div>
JQuery
$(document).ready(function() {
// in reality this contnet will be returned from ajax call
var dynamicContent ="<div><button id='btn' type='button'>Click Me</button></div>"
var myWindow = $("#window")
var button = $(dynamicContent).find("#btn");
// show number of buttons found.
alert("found " + button.length + " button")
// attach click event to button
button.click(function(){
alert("this is test");
})
myWindow.kendoWindow({
width: "600px",
height:"200px",
title: "My Window"
}).data("kendoWindow").center().open().content(dynamicContent);
});
You need to change:
button.click(function(){
alert("this is test");
})
to
$('#window').on('click', 'button', function(){
alert("this is test");
})
As you mentioned the element is dynamically created, so it is not part of the browsers dom structure, and therefore can't be selected with jQuery. Using the above code, jQuery listens for any changes to the dom structure inside the #window element, so you can then select any dynamically created elements.

JQueryUI how to 'self' close a dialog

I'm working on a web app that uses jQueryUI and creates a ton of dialogs. The dialogs are all different, and the button to close the dialog can end up embedded several div's into the dialog.
I'd like a function that always closes the containing dialog.
Take for example the following html:
<div id="demoDialog">
<div>
<div id='demoDialogSubmit'>
<input type='submit' onClick='selfCloseDialog();' value='Ok' style='margin-top:10px' />
</div>
<div>
<div>
Somewhere in my js code I initialized this as a dialog:
$( "#demoDialog" ).dialog( params );
Now for the on-click I have a few not so great choices. I could insist on the close button knowing the id of the dialog. E.g. do something like:
onclick="$( '#demoDialog' ).dialog( 'close' );"
But I'd rather have generic code instead of always having to carry around the id of the dialog so I can send it to a widget that may close it.
Or I can remember how many layers down I am:
function selfCloseDialog() { $(this).parent().dialog( 'close' ); }
But really I want selfCloseDialog() to just hunt up the layers of elements looking for the dialog object to close. How do I do this?
#Update:
So i got it working. Thanks everyone for their suggestions the problem actually had two issues.
First one problem was here:
<input type='submit' onClick='selfCloseDialog();' value='Ok'/>
It should be:
<input type='submit' onClick='selfCloseDialog(this);' value='Ok'/>
The button element is not passed in as the "this" argument to the function. Which seems obvious now.
And the following direct method JAAulde below works and seems the cleanest:
function selfCloseDialog( caller ) {
$(caller).closest( ".ui-dialog-content" ).dialog('close');
}
There were several answers involving closest and a selector- but I don't see any reason to use anything except the plain class selector he suggests.
When making your dialog, include a close button:
var params = {
//whatever you already had in there
buttons: {
// In the buttons object, the "key" will be the button text, the function
// will be executed on click of the button in scope of the dialoged element
Close: function () {
$(this).dialog('close');
}
}
};
$( "#demoDialog" ).dialog( params );
And from code running in scope of ANY descendant element of the dialoged element, run:
$(this).closest('.ui-dialog-content').dialog('close');
Not sure if I'm exactly understanding what you're asking, but it seems the easiest way would be to add a standard class to all your dialogs, and then have code like:
$(this).closest('.dialog-class').dialog('close');
closest() is defined here:
http://api.jquery.com/closest/
*updated to reflect the ajax part of the dialog. *updated to reflect comments
<div id="soemthing.random.ui.dialog.makes">
.... your content....
<a class='custom-close' href="#Close">Custom Close</a>
....
</div>
$(function(){
$("your selector").dialog();
var selector = ":ui-dialog";
//developers choice. ".ui-dialog-content" is faster, ":ui-dialog" is guaranteed
$(selector ).on({
"click":function(event){
event.preventDefault();
$(this).closest(selector).dialog("close");
}
},"a.custom-close",null);
})
I'd suggest using a class instead of writing inline function calls, but that's up to you.
Here's my hackish solution with event delegation where clicking an element with the selfclose class will close the ancestor dialog:
$(document).on('click', '.selfclose', function() {
$(this).parents().each(function() {
try {
$(this).dialog('close');
} catch(e) {}
});
});
Fiddle
But as DefyGravity mentioned, using the :ui-dialog selector is a much cleaner solution:
$(document).on('click', '.selfclose', function() {
$(this).closest(":ui-dialog").dialog("close");
});
Fiddle
check this:
http://jsfiddle.net/Wqh4Y/3/
function closeParentDialog(closeButton)
{
closeButton.parents('.ui-dialog').eq(0).find('a.ui-dialog-titlebar-close').eq(0).click();
}
$(function() {
$( "#dialog" ).dialog();
});​
you can use it like this:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.
<span> <a class="close-dialog" onclick="closeParentDialog($(this))">selfclose</a> </span>
</p>
</div>

Is there any callback function on click?

Let's say I have the following link:
<a href="#shippingaddress" onclick="return validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);" >
EDIT
i am using multi page approach to show different section(divs) as a page
in that validate function I am validating the form and if everything is ok then displaying a hidden <div> and after the <div> is visible <spans> are getting applied by jquery mobile framework, untill and unless that div is hidden there is no span, but as that div become visible jquery mobile gets applied on it and appended some spans..i need to access this spans :
<span>blah</span>
So I want to change the text of this <span> after the click event, because the <span> is displayed after the click event.
So is there any way to do this?
In your validate function you can do this:
<div id="someDiv" style="display:none">
<span id="someSpan"></span>
</div>
<script type="text/javascript">
function validateBillingAddress() {
var valid = true;
... // do whatever you need to validate your input here and update valid variable
if (valid) {
$('#someDiv').show();
// if the validation is succesful invoke some function in the framework here
$.ajax({
...
success: function() {
//append the span to the div here
$(#someDiv').append('The span HTML content');
},
...
});
}
}
</script>
You could actually embed the validateBillingAddress into another function, containing the "callback" line as well
function doValidate( event ) {
validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);
$('#spanElement').text( 'new text' );
}
And then
<a onclick="return doValidate( event );" >
Would be even better if you avoided using the onclick property in favor of a non-invasive event handling like
$('#aElement').click( function( e ) {
doValidate( e );
});
Do not use inline javascript...
$("#validate").click(function(){
// validate billing address
});
<a id="validate">Validate</a>
To create a span and attach a listener to it, then append to the div:
$("<span />").click(function(){
$(this).text("New Text");
}).appendTo("#divToShow");
Edit:
Since you haven't provided much information, the only thing I can help you out is:
1- To access all spans within the div, you do:
$("#myDivId span")
2- To access only spans that are direct children of the div, you do:
$("#myDivId > span")
3- To access only the last span within the div, you do:
$("#myDivId span:last")
More than that, only if you provide some actual generated code

why jquery detach element will cause a form to submit?

i wonder why in the following example, trying to detach an element (li) causes the form containing it to submit
html
<form id="frmToDo" name="frmToDo">
<p id="lineInput">
...
<input type="submit" id="btnSubmit" value="Add" />
</p>
<ul id="todolist">
<!-- added in ajax -->
</ul>
</form>
JS
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
I guess you just want to remove the li element in which the button was clicked.
So instead of using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
Try using
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$(this).parent().detach();
return false;
});
That's not a button, it's an input element.
$("#todolist").delegate("li[id^=task-] input:submit", "click", function() {
I am not sure if this is the cause of your problem but you are not using the detach function correctly if your intention is to detach an li element. The argument of the detach function is a selector expression that filters the set of matched element in the jQuery element that you are calling the function on. In your code you call detach on $('#todolist'), which means you want to detach the todolist element, if it matches the argument passed.
You should do something like this instead :
$('#todolist li').detach(); //this will detach all the li elements
I am not sure if this can explain the fact that your form is submitting. If it is not : what event triggers the submit event of your form ? Maybe you use a button or input element that is placed inside the form and triggers the submit of the form ?
Unless there's some relevant code missing, you seem to assign a handler to the onclick event outside a $(document).ready() block. That makes it possible to run the assignment before the #todolist is loaded, thus failing to find the buttons and attach handlers.
With no event cancelling, the default behaviur for a button is to submit the form.
Try this:
$(document).ready(function(){
$("#frmToDo").submit(function() {
// this runs after: $("#todolist").detach(...)
});
$("#todolist").delegate("li[id^=task-] button", "click", function() {
$("#todolist").detach($($(this).parent()).id());
return false;
});
});

Categories

Resources