How to make "modal conformation" functionality in this function call? - javascript

When i m calling this below function in script, i will get a popup dialog box to do some instructions.
Here is my sample code:
function updateStatus(instrxnID){
exporter.fn.childWindow({
instrxnID : instrxnID,
url:'pgks/fund/update/view.page'
},'pgks','Popup',{top:100,height:459,width:884,left:200});
}
exporter.fn.childWindow will call the below function to open popup'
childWindow : function(elements,path,title,setting){
setting = setting != undefined ? setting : {top:100,height:300,width:400,left:200};
var keys = exporter.fn.keys(elements);
var offset = "width="+setting.width+",height="+setting.height+",top="+setting.top+",left="+setting.left;
myWin = open("", "displayWindow", offset+",scrollbars=no,status=no,dependent=yes,directories=no,menubar=no,personalbar=no");
myWin.document.open();
myWin.document.write("<html><head>");
myWin.document.write("</head><body><form name='form' action='"+elements.url+"' type='post'>");
for ( var a = 0; a < keys.length; a++) {
myWin.document.write('<input type="hidden" name="'+keys[a]+'" value="'+elements[keys[a]]+'">');
}
myWin.document.write("</form><script type='text/javascript'>form.method=\'post\';form.submit();</script></body></html>");
myWin.document.close();
}
After finishing those instruction ,i should return to the main page or parent page of this popup.
Note: By clicking background page or another link, this modal should not disapper.
Example: i need to attain something like this example

Attach either a click handler to your submit buttons, or a submit handler to the form. In this handler hide (display: none;) your popup or, if you're using a window object for your pop up, call .close() on the instance.
EDIT:
$(".my-button").on("click", function() {
myWin.close();
});

Related

Binding listener to a dynamically created element

I am using bootstrap's list group to create a row of tabs. When someone clicks on an element in a table, it dynamically creates a new tab and appends it to that list group.
var newtext = "#"+ticket+" - "+parele.find("td:nth-child(3) strong").html();
var closebtn = $("<button>").addClass("close ml-2 mr-n2 newlyaddedclose").html("×");
var newdiv = $("<div>").addClass("d-flex justify-content-between").append(newtext).append(closebtn);
var newa = $("<a>").addClass("list-group-item list-group-item-action").attr("data-toggle","list").attr("href","#ticket"+ticket).attr("id","ticket"+ticket+"-tab").append(newdiv);
$("#ticketpanel").append(newa);
The problem I am having is the newly created close button. I need to bind a function that identifies when that is clicked to handle closing that tab, but it doesn't seem to be working. In my example here, I added the "newlyaddedclose" class to help identify the new element temporarily and I added the following code below to bind a function that is defined at the top of my script tag:
$(".newlyaddedclose").on("click",".close",closebtn).removeClass("newlyaddedclose");
This still doesn't work. When I inspect the close button element, console shows this error: Framework Event Listeners API Errors:
event listener's handler isn't a function or empt
Am I making this harder than it needs to be, or what am I doing wrong? I can simple put at the end of this element creation this:
$(".close").click(function() { ... });
But doing this starts to double up and triple up etc, those events on already created tabs.
EDIT:
Here is my entire block of script to clear up any confusion.
$(function() {
function closebtn() {
alert("Close button clicked...");
}
$(".ticket-line").click(function() {
var parele = $(this);
var ticket = parele.data("tnum");
// Check to see if ticket is already open in tabs
if($("#ticket"+ticket).length == 0) {
// Create tab on ticket panel
var newtext = "#"+ticket+" - "+parele.find("td:nth-child(3) strong").html();
var closebtn = $("<button>").addClass("close ml-2 mr-n2 newlyaddedclose").html("×");
var newdiv = $("<div>").addClass("d-flex justify-content-between").append(newtext).append(closebtn);
var newa = $("<a>").addClass("list-group-item list-group-item-action").attr("data-toggle","list").attr("href","#ticket"+ticket).attr("id","ticket"+ticket+"-tab").append(newdiv);
$("#ticketpanel").append(newa);
$(".newlyaddedclose").on("click",".close",closebtn).removeClass("newlyaddedclose");
// Create DIV with content
var newdata = $("<div>").addClass("tab-pane").attr("id","ticket"+ticket);
$("#ticket-tabs").append(newdata);
$("#ticket"+ticket+"-tab").tab("show");
} else {
// Ticket is already open, switch to it instead
$("#ticket"+ticket+"-tab").tab("show");
}
});
})
The error is clearly stating you are binding a non function to the event listener. So the error is saying that closeBtn is not a function. Your code, you defined closeBtn as the button you are trying to attach the event too. So change closeBtn in the click event listener to the name of the function you are actually trying to call. If it is the same function name, rename something.
Your problem:
var closeBtn = 1;
if (1===1) {
var closeBtn = 2;
console.log(closeBtn);
}
console.log(closeBtn);
It is unclear why you are selecting the element you just added. You can just attach the event when you create the button, no need to look up the element.
var closebtn = $("<button>")...
closeBtn.on("click", function (){
console.log('clicked', closeBtn);
});
Or use event delegation so any element you add will trigger the function.
$("#ticketpanel").on("click", ".close", function () {
const closeBtn = $(this);
console.log('clicked', closeBtn);
});

Using event in jQuery custom function

I'm making a popup system and I'm having some issues with using event as an attribute in my custom function. Here is my code:
var openLayoutPopup = function(event){
event.preventDefault();
var target = $(event.target);
var flexible_field = target.closest('.acf-field-flexible-content').attr('data-key');
var popup = $('.'+flexible_field);
var overlay = $('.bbh-popup-overlay');
popup.addClass('open').fadeIn();
overlay.fadeIn();
}
$('.my-class').click(openLayoutPopup(event));
But my console gives me the following error saying event isn't defined:
ReferenceError: event is not defined
I've used event.target before and event.which, but only for unnamed functions.
Additionally, I have another similar function, in which I need to pass event and a secondary boolean parameter:
function closeLayoutPopup(event, openLayout){
event.preventDefault();
var popup = $(event.target).closest('.bbh-popup');
var overlay = $('.bbh-popup-overlay');
popup.removeClass('open').fadeOut();
overlay.fadeOut();
if(open == true){
var dataLayout = target.attr('data-layout');
acf.fields.flexible_content.add(dataLayout);
}
}
Similarly I'm confused about how to pass the parameters in that one.
EDIT:
What I was trying to do explained shortly is having a button open a popup. Popup has two buttons, one to close popup and one to add layout to page and close afterwards. Issue was me calling functions wrong, and not realizing my solution was illogical.
I fixed the click events thanks to #Raibaz. Then I added to closeLayoutPopup to the addLayout function instead of combining them:
/*==============================================
= Function - Close popup =
==============================================*/
function closeLayoutPopup(event){
event.preventDefault();
var popup = $(event.target).closest('.bbh-popup');
var overlay = $('.bbh-popup-overlay');
popup.removeClass('open').fadeOut();
overlay.fadeOut();
}
/*=============================================
= Function - Open popup =
=============================================*/
var openLayoutPopup = function(event){
event.preventDefault();
var target = $(event.target);
var flexible_field = target.closest('.acf-field-flexible-content').attr('data-key');
var popup = $('.'+flexible_field);
var overlay = $('.bbh-popup-overlay');
popup.addClass('open').fadeIn();
overlay.fadeIn();
}
/*=============================================
= Function - Add Layout =
=============================================*/
var addLayout = function(event){
event.preventDefault();
var target = $(event.target);
var dataLayout = target.attr('data-layout');
acf.fields.flexible_content.add(dataLayout);
closeLayoutPopup();
}
/*---------- add section click - open popup ----------*/
$('.acf-field-flexible-content .acf-flexible-content > .acf-actions a.acf-button').on('click',openLayoutPopup);
/*---------- Close button click ----------*/
$('.layout-picker-close').on('click', closeLayoutPopup);
/*---------- Add layout ----------*/
$('.bbh-popup a.add-layout-button').on('click', addLayout);
I'm assuming you want to open the layout popup when clicking on elements with the my-class class, so your code should be something like this:
$('.my-class').on('click', openLayoutPopup);
The event parameter will be passed to the function when invoking the openLayoutPopup callback function.
You can have a look at the documentation for jQuery.on for reference.
As for the other function, instead of passing a second boolean parameter to the click event handler you could use a custom CSS class or a data attribute to indicate that there is an open popup, so your openLayoutPopup function could contain something like this:
$('body').addClass('has-popup')
and in your closeLayoutPopup you could just check if the class is present to determine if there is an open popup, and eventually remove it when closing the popup.

Bootstrap Modal not adding modal-open class to body when triggered via Javascript

I have a Modal on my page whose content changes depending on which of two buttons is clicked (an <input />'s value changes). To better add functionality, I have set up an additional block of that is supposed to manual open the Modal if there's an error to show.
To make sure the form is "sticky", I manually trigger the click event on the corresponding button and what not. However, when I manually trigger the click event, Bootstrap is not adding .modal-open to the body. Due to how my site is built, without .modal-open on the body, the Modal is completely hidden behind other content.
So obviously I'm doing something wrong, but I have no idea. Here's a copy of my code:
<?php
$modalerror = false;
$id = 0;
if (/*Basic check for errors*/) {
$modalerror = true;
$id = /*Get the correct id*/;
}
?>
<script type="text/javascript">
jQuery( document ).ready(function($) {
$('#modal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
if (button.attr('data-name') && button.attr('data-name') != '') {
$('#name').val(button.attr('data-name'));
} else {
$('#name').val('');
}
});
});
<?php if ($modalerror) { ?>
jQuery ( window ).load(function() {
jQuery('button[data-id=<?php echo $id; ?>]').trigger('click');
});
<?php } ?>
</script>
Upon further inspection/progress, I noticed that it I manually trigger the Modal in the exact same fashion somewhere else on the page/later on, there aren't any problems with adding the .modal-open class to the body. Code sample:
<script type="text/javascript">
function manualOpen(id) {
jQuery('button[data-id="'+id+'"]').trigger('click');
}
</script>
<button type="button" onclick="manualOpen(/*Correct id*/);">Open</button>
Even more testing, I added a second modal to the page with completely different contents that opens automatically under very specific circumstances, it does not need to load custom content based off of a buttons data-* attributes. This second Modal suffers the exact same problem if it doesn't also have some form of timeout (as mentioned in my comment to this question).
Using bootstrap 4, the best way IMO without using timeouts is adding a function in the closing event of the modal.
When a modal is closing and there is a command for open another modal before it completes the closing action, the new modal is open but the class .modal-open is not added to the body.
The next function open a modal checking if there is an opened modal. The new modal is opened directly or in the closing event callback depending of the case. This function requires that every modal has an id.
function openModal(modalid) {
//Looks for current modal open
if ($('.modal.fade.show').length > 0) {
//Gets the id of the current opened modal
var currentOpenModalId = $('.modal.fade.show').attr('id');
//Attaches a function to the closing event
$('#' + currentOpenModalId).on('hidden.bs.modal', function () {
//Opens the new model when the closing completes
$('#' + modalid).modal('show');
//Unbinds the callback
$('#' + currentOpenModalId).off('hidden.bs.modal');
});
//Hides the current modal
$('#' + currentOpenModalId).modal('hide');
} else {
//If is not an opened modal, the new modal is opened directly
$('#' + modalid).modal('show');
}
}
I am using Bootstrap 4.1.1 and jQuery 3.3.1, and faced the same problem. 50ms didn't solved the problem. So, i had to bump it upto 500ms, and it worked!
//hide first
$('#modal1').modal('hide');
//add delay when showing next modal
setTimeout(function () {
$('#modal2').modal('show');
}, 500);
I'm using bootstap 4.3.1 and modified 'bootstrap.min.js' file
//bootstrap.min.js (line : 1646)
this._showBackdrop(function () {
g(document.body).removeClass(ce); // ce = 'modal-open'
t._resetAdjustments(),
t._resetScrollbar(),
...
to
//bootstrap.min.js (line : 1646)
this._showBackdrop(function () {
if (document.getElementsByClassName('modal fade show').length == 0) {
g(document.body).removeClass(ce);
}
t._resetAdjustments(),
t._resetScrollbar(),
...
It works very well

Preventing javascript callback from being called on parent div

I'm working on a userscript which is supposed to be cross-browser compatible which might explain why I'm not doing things the normal way. The script displays a floating div named box which is a jQuery object. The click function looks like this:
box.click(function(event) {
set_visible(false);
});
The set_visible function just does a box.fadeOut(500);
Inside the parent div I create a menu not using jQuery but plain old javaScript using an array of functions like so (I tried rewriting this function using jQuery but had some issues getting the array functions to work):
function doGMMenu() {
if( !GM_falsifiedMenuCom.length ) { return; }
var mdiv = document.createElement('div');
for( var i = 0; GM_falsifiedMenuCom[i]; i++) {
var bing;
mdiv.appendChild(bing = document.createElement('a'));
bing.setAttribute('href','#');
bing.onclick = new Function('GM_falsifiedMenuCom['+i+'][1](arguments[0]); return false;');
bing.appendChild(document.createTextNode(GM_falsifiedMenuCom[i][0]));
if (i+1<GM_falsifiedMenuCom.length)
mdiv.appendChild(document.createTextNode('\u00A0\u00A0|\u00A0\u00A0'));
}
status.contents().append(mdiv);
}
Here's an example of the first array function which displays an options menu:
function() { DisplaySlideMenu(true); }
My problem is that when I click on the link, the options menu displays, but the parent divs box.click function is also called which hides it when I don't want to. When the anchor .onclick function is added you can see that the last entry is return false; but that doesn't prevent the .click event from propagating up to the parent div. Is there any way to prevent this from happening?
box.click(function(event) {
event.stopImmediatePropagation();
event.stopPropagation();
set_visible(false);
});

Why alert popup a few times after a click event?

On a page there are couple of Add buttons (li .plus).
When you click on a Add button and assume json.success is false, it will then popup via $.colorbox plugin
The popup pull the data from href:"/Handle/Postcode/?val" + Val
There is a submit button (#submitButton) from the popup, when I click on the submit button, it keep popup alert box a few times, I dont understand why that happen? how to fix it?
$("li .plus").click(function(event) {
event.preventDefault();
var Val;
Val = $('#id').val()
$.getJSON(Address +"/Handle/Add", {
Val:Val
}, function(json) {
if (json.success == "false" && json.error == "NoArea") {
$.colorbox({
width:"450px",
transition:"none",
opacity:"0.4",
href:"/Handle/Postcode/?val" + Val
});
$("#submitButton").live('click', function() {
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
//Why does it popup a few times?
});
}
if (json.success == "true") {
Backet();
}
});
});
Thats an easy one, because you are using the .live() function to bind your click handler. If that code gets executed more than one time your binding happens more than one time.
You can either try to track the state of the binding and only apply it if it doesn't exist, or you can call your click function in the html with the onClick attr.
Edit: Just to clarify I meant something along the lines of -
HTML
<button id='submitButton' onclick="displayAreaCode();">Submit</button>
JS
function displayAreaCode(){
var PostCodeArea = $("#deliveryAreaPostcode").val();
alert(PostCodeArea);
}

Categories

Resources