Javascript + click function - javascript

I have a javascript function that calls another function, I am now facing a problem where I have to click a button twice to display a modal dialog box, I know the issue most likely lies in this line:
$('#dialog_link').click(function() because I already called 'modaldialog' with an onclick like this:
<input id="dialog_link" type="button" value="Save" onclick ="javascript:modaldialog();" />
How can I rewrite this line $('#dialog_link').click(function() to call function() without another click?
Thanks!
<script type="text/javascript">
function modaldialog() {
window.Page_ClientValidate();
if (window.Page_IsValid) {
$('#dialog_link').click(function() {
$('#dialog').dialog('open');
return false;
});
}}
</script>
<script type="text/javascript">
$(function() {
// Accordion
$("#accordion").accordion({ header: "h3" });
// Tabs
$('#tabs').tabs();
// Dialog
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal:true,
close: function() {
document.getElementById('dialog').style.display = 'block';
document.getElementById('fade').style.display = 'None';
},
buttons: {
"Ok": function() {
$(this).dialog("close");
document.getElementById('dialog').style.display = 'block';
document.getElementById('fade').style.display = 'None';
},
"Cancel": function() {
$(this).dialog("close");
document.getElementById('dialog').style.display = 'block';
document.getElementById('fade').style.display = 'None';
}
}
});
// Dialog Link
//$('#dialog_link').click(function() {
// $('#dialog').dialog('open');
// return false;
//});
// Datepicker
$('#datepicker').datepicker({
inline: true
});
// Slider
$('#slider').slider({
range: true,
values: [17, 67]
});
// Progressbar
$("#progressbar").progressbar({
value: 20
});
//hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
</script>

I'm not sure what your goal really is, but I don't think .click(func) does what you think it does. Since .click(func) adds that function as a click event listener every time you execute this line you would get an additional function in the listener set. You seem to be running this in your onClick meaning every time someone clicks your link you'll add another listener that does the same thing ($('#dialog').dialog('open');). If you just want your verification to be done before substituting the onClick handler you'll have to unbind the current function as well, but you might be better off just doing the check every time and calling $('#dialog').dialog('open') inside your if (window.Page_IsValid) block.
If what you really want is for modaldialog to be called only once and $('#dialog').dialog('open'); to be executed that time and every consecutive clicks do the following inside your conditional:
$('#dialog_link').unbind('click', this);
var f = function () { $('#dialog').dialog('open') }; // Function to replace onClick function.
$('#dialog_link').click(f);
f(); // Execute replacement function after assigning it.

Related

jQuery ("#dialog").dialog('close') not working with button on separate view

I have an ASP.NET view in an MVC project in which I am trying to create a pop-up dialog to create data. There is another view that gets loaded and that view has a button with the id "btncancel_create". I cannot get that button to close the dialog. I am using jQuery 2.1.3 and jQuery UI 1.11.4.
Here is the code for the button:
<input type="button" value="Cancel" id="btncancel_create" />
And here is the view:
$(document).ready(function () {
//alert("Document is ready");
var url = "";
$("#dialog-create").dialog({
title: 'Create User',
autoOpen: false,
resizable: false,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
}
});
$("#lnkCreate").on("click", function (e) {
url = $(this).attr('href');
$("#dialog-create").dialog('open');
return false;
});
//$("#btncancel_create").on("click", function (e) {
// $("#dialog-create").dialog("close");
// return false;
//});
$("#dialog-create").button("#btncancel_create").click(function (e) {
alert("btncancel_create was clicked");
$("#dialog-create").dialog('close');
return false;
});
});
<div id="dialog-create" style="display: none"></div>
<p>#Html.ActionLink("Create New", "Create", null, new { id = "lnkCreate" })</p>
As you can see, I tried something else which didn't work, which is commented out. The uncommented button click function does return the alert, but does not close the dialog. Thanks in advance for your help, and please let me know if you need any more information.
Instead of
$("#btncancel_create").on("click", function (e) {...
(in my commented out code above)
it should be
$(document).on("click", "#btncancel_create", function (e) {....
I found the answer here: Turning live() into on() in jQuery.

How to stop animation after one body click with jQuery

So, i have some animation actions, this is for my login panel box:
$('.top_menu_login_button').live('click', function(){
$('#login_box').animate({"margin-top": "+=320px"}, "slow");
});
$('.login_pin').live('click', function(){
$('#login_box').animate({"margin-top": "-=320px"}, "slow");
});
now i need to add some hiding action after click on body so i do this:
var mouse_is_inside = false;
$('#login_box').hover(function () {
mouse_is_inside = true;
}, function () {
mouse_is_inside = false;
});
for stop hiding this element on body click, and this for body click outside by login-box
$("body").mouseup(function () {
if (!mouse_is_inside) {
var login_box = $('#login_box');
if (login_box.css('margin-top','0')){
login_box.stop().animate({"margin-top": "-=320px"}, "slow");
}
}
});
Everything is fine but this panel animates after each body click, how to stop this and execute only one time? Depend on this panel is visible or not?
You'd normally do this sort of thing by checking if the click occured inside the element or not, not by using mousemove events to set globals :
$(document).on('click', function(e) {
if ( !$(e.target).closest('#login_box').length ) { //not inside
var login_box = $('#login_box');
if ( parseInt(login_box.css('margin-top'),10) === 0){
login_box.stop(true, true).animate({"margin-top": "-=320px"}, "slow");
}
}
});
And live() is deprecated, you should be using on().

dialog is not a function error

I have this JavaScript code which I use for question dialog:
// Question Dialog
function deletedialog(button, a){
$("<div />", {
text: a
}).dialog({
width: 600,
buttons: {
"Ok": function() {
$(button).closest("form").find("[id$=deleterow]").click();
$(this).dialog("close");
button.value = "Processing...";
button.disabled = true;
},
"Cancel": function(event) {
$(this).dialog("close");
event.preventDefault();
button.value = "Delete";
button.disabled = false;
}
}
});
}
But for some reason that I cannot find I get this error in Firebug:
TypeError: $(...).dialog is not a function
and this row is highlighted
"Cancel": function(event) {
This problem occurs when I added this in the JSF head in order to prevent JQuery and Primefaces conflict:
<script type="text/javascript">
$.noConflict();
</script>
How I can solve this problem?
The problem
The problem is that the $ symbol has been removed by using $.noConflict() function. Use jQuery instead.
Two solutions
This basically means you should write function calls like jQuery(this).dialog("close"); instead of $(this).dialog("close");.
To implement the change for the bigger piece of code, you can do it like that:
(function($){
// ... old code using "$" instead of "jQuery"
})(jQuery);
Solution no. 1 - multiple replacements - example
The solution with replacing $(...) calls with jQuery(...) could look like this:
// Question Dialog
function deletedialog(button, a){
jQuery("<div />", {
text: a
}).dialog({
width: 600,
buttons: {
"Ok": function() {
jQuery(button).closest("form").find("[id$=deleterow]").click();
jQuery(this).dialog("close");
button.value = "Processing...";
button.disabled = true;
},
"Cancel": function(event) {
jQuery(this).dialog("close");
event.preventDefault();
button.value = "Delete";
button.disabled = false;
}
}
});
}
Solution no. 2 - enclosing code in anonymous function - example
This is based on the fact you can create anonymous function and pass jQuery to it, but assign it to the argument called $ - which will result in $ symbol available within the function as if it would happen before $.noConflict() call:
(function($){
// Question Dialog
function deletedialog(button, a){
$("<div />", {
text: a
}).dialog({
width: 600,
buttons: {
"Ok": function() {
$(button).closest("form").find("[id$=deleterow]").click();
$(this).dialog("close");
button.value = "Processing...";
button.disabled = true;
},
"Cancel": function(event) {
$(this).dialog("close");
event.preventDefault();
button.value = "Delete";
button.disabled = false;
}
}
});
}
})(jQuery);
Before $.noConflict();, $ is equal to jQuery.
After $.noConflict();, $ is equal to undefined.
This removes the $ shortcut to jQuery, and that is why it is not a function anymore. You typically only use $.noConflict(); when you add another javascript library that uses $. Your options are:
Don't use $.noConflict();.
Use $.noConflict(); and replace every $ with jQuery.
Use $.noConflict(); and wrap your code with (function($){ ... })(jQuery)
If you need to use $.noConflict();, I suggest using the third one. It remaps $ to jQuery by passing jQuery as a parameter. Using the code you posted, it may look something like...
(function($){
// Question Dialog
function deletedialog(button, a){
$("<div />", {
text: a
}).dialog({
width: 600,
buttons: {
"Ok": function() {
$(button).closest("form").find("[id$=deleterow]").click();
$(this).dialog("close");
button.value = "Processing...";
button.disabled = true;
},
"Cancel": function(event) {
$(this).dialog("close");
event.preventDefault();
button.value = "Delete";
button.disabled = false;
}
}
});
}
})(jQuery)

jQuery ajax form submitting multiple times

I am having some issues with multiple form submissions with a jQuery/ajax form. I found this by printing every instance of form submission on my server, and saw that a form would submit correctly once, then again multiple times.
Just to be clear, this code works 100% correctly for the first submission, but when I click on another row in my table, and create a new dialog/submit it, it ends up submitting multiple times.
I think it has to do with event binding, but am having trouble fixing it. Any insight or help would be much appreciated.
The button's id is "save-flag-button"
// When someone clicks on the flag column in my table, a dialog pops up //
// on the condition that a flag does not exist. //
$(function() {
$('.flag').click(function() {
var cellId = "flag" + String(this.getAttribute("data-client-rel"));
if (this.getAttribute("data-flag-exists") == '0') {
// create dialog
var dialog = flagDialog('Create Flag');
// Making the form ajax
$("form", dialog).ajaxForm(function(success, data) {
if (success) {
$("#" + cellId).attr("data-flag-exists", '1');
$("#" + cellId).attr("data-flag-content", data["flag_state"]);
$("#" + cellId).text(data["flag_state"]);
$("#flag-dialog").dialog("close");
} else {
alert("Failed to submit flag. Please retry.");
}
});
} else { }
}).hover(function() {
if (this.getAttribute("data-flag-exists") == '0') {
this.innerHTML = '<span style="color: #4183C4;">Create flag!</span>';
}}, function() {
this.innerHTML = this.getAttribute("data-flag-content");
})
});
// jquery dialog code //
function flagDialog(dialogTitle) {
var dialog = $("#flag-dialog").dialog({
autoOpen: false,
autoResize: true,
modal: true,
minHeight: 300,
minWidth: 450,
position: "center",
title: dialogTitle,
buttons: [{
id: "flag-cancel-button",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
},
{
id:"save-flag-button",
text: "Submit",
click: function() {
$("#flag-dialog").dialog("destroy");
// $("#client-relationship-flag-form").submit();
}
}],
close: function() {
//$("#notes-text").text("");
}
});
// Unbinding buttons here //
$("#save-flag-button, #flag-cancel-button").unbind();
$("#save-flag-button").unbind('click').click(function() {
$("#client-relationship-flag-form").submit();
});
$("#flag-cancel-button").click(function() {
$("#flag-dialog").dialog("close");
});
dialog.dialog("open");
return dialog;
};
ajaxForm binding should be done once only.
Try to put the ajaxForm binding on $(document).ready event and try to restructure your logic. ajaxForm was bind every time you click .flag element and all previously bind ajaxForm would be called on all succeeding click event.

Return value of jquery UI dialog Box

You may find solution over this in many posts(Post 1 , Post2 ), but their solution not working for me.
Here is the normal jquery dialog box written by me.
$("#dialog").dialog({
autoOpen:false,
buttons:{
"ok":function(){
$(this).dialog("close");
return true;
},
"cancel":function(){
$(this).dialog("close"); return false;
}
}
});
I will open the dialogbox with code:
var returnVal=$("#dialog").dialog("open");
I need to return false,if user clicks 'cancel' and return true if user clicks 'ok'.
var returnVal=$("#dialog").dialog("open");
I NEED returnVal to return boolean value(true/false), but it returns javascript object.
You cannot return something from the OK / cancel functions as they are essentially event handlers that are only processed upon the click of a button.
Use a separate function to process the result :
$mydialog = $("#dialog").dialog({
autoOpen: false,
buttons: {
"ok": function() {
$(this).dialog("close");
processResult(true);
},
"cancel": function() {
$(this).dialog("close");
processResult(false);
}
}
});
$mydialog.dialog("open");
function processResult(result) {
alert(result);
}
Working example : http://jsfiddle.net/nz2dH/
I have implement Yes/No confirmation dialog with custom message and callback function like this. This is useful, if you like to use the same dialog for various purposes.
<script type="text/javascript">
// prepare dialog
$(function () {
$("#confirm-message-dialog").dialog({
autoOpen: false,
modal: true,
closeOnEscape: false,
buttons: {
Yes: function () {
$(this).dialog("close");
$(this).data("callback")(true);
},
No: function () {
$(this).dialog("close");
$(this).data("callback")(false);
}
}
});
});
// open dialog with message and callback function
function confirmMessageDialog (message, callback) {
$('#confirm-message-dialog-message').text(message);
$('#confirm-message-dialog').data("callback", callback).dialog("open");
};
</script>
<!-- The dialog content -->
<div id="confirm-message-dialog" title="Warning">
<p id="confirm-message-dialog-message"></p>
</div>
Hope that this helps others as well :)

Categories

Resources