How to make checked a checkbox which is in closed modal? - javascript

I have this modal :
<div class="modal fade" id="column-settings-modal" tabindex="-1" role="basic" aria-hidden="false">
And this checkbox in the modal :
<input type="checkbox" id="partcountry-cb" value="Ülke"/> Ülke <br />
I have a function to load modal. And I want to check this checkbox while modal is opening. My function is below :
function load_column_filters(surveyId,toShow) {
var $modal = $('#column-settings-modal');
$modal.modal();
$("#partcountry-cb").attr("checked", true);
}
However, the last statement does not work. (I have tried .prop,but it did not work.) Is this problem about modal itself or am I missing something?

Are you using bootstrap modal? If yes, try check out this event doc for modal. Try modified it content when it completely open by triggering shown callback like so :
function load_column_filters(surveyId,toShow) {
var $modal = $('#column-settings-modal');
$modal.modal();
}
$('#column-settings-modal').on('shown.bs.modal', function() {
$("#partcountry-cb").prop("checked", true);
});

Related

Pass dataset attribute from anchor tag all the way down to bootstrap modal button

I have an <a> tag that toggles the show/hide of a Bootstrap Modal.
Where emailFoo modal looks like
<div class="modal fade" id="emailFoo">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-footer">
<button id="sendEmail">OK</button>
</div>
</div>
</div>
</div>
I want to obtain the data of FOO upon the clicked event of an #email button inside the #emailFoo
How can I get the value of the foo from the button that opened the modal in the #sendEmail click event?
$( "#sendEmail" ).click(function() {
//Get foo here from Parent modal that button is inside
//$('#emailFoo').dataset['foo']
});
As a workaround I can obtain foo from when the modal is first opened. I was thinking I can then set this value somewhere else so that the button click can get it.
I.e.
$('#emailFoo').on('show.bs.modal', function () {
//This works! How can I do the same thing from the `sendEmail` click event above?
const callerFromAnchorTag = $(e.relatedTarget);
const foo = callerFromAnchorTag [0].dataset['foo'];
});
it seems you want to get the foo value in this way:
$( "#sendEmail" ).click(function() {
const btn = $(this);
const modal_id = btn.parents('.modal').attr('id');
let toggler = $('body').find('[data-target="#' + modal_id +'"]');
console.log(toggler.attr('data-foo'));
});
UPDATE:
new part:
so we have several toggler in a page, you want to detect witch toggler is the caller of modal?
A fancy way to achieve this (by js objects):
class Modal {
constructor(selector) {
this.$modal = $(selector);
this.modal_id = this.$modal.attr('id');
this.$toggler = null;
this.init();
this.events();
}
init() {
const obj = this;
}
events() {
const obj = this;
$('[data-toggle="modal"]').on('click', function () {
const $a_toggler = $(this);
if ($a_toggler.attr('data-target') === '#' + obj.modal_id)
obj.$toggler = $(this);
});
}
get_toggler() {
return this.$toggler;
}
}
usage:
making new modal object (at first of your code):
const my_modal = new Modal($('#emailFoo'));
returning toggler jquery object (wherever you want to get it):
console.log(my_modal.get_toggler());
another simple way:
make a hidden input inside your modal like this:
<div class="modal fade" id="emailFoo">
<input type="hidden" class="js-toggler__input" value="" hidden>
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-footer">
<button id="sendEmail">OK</button>
</div>
</div>
</div>
</div>
after clicking on togglers, save its id or some attribute like data-toggler="__toggler-number__" (I used data attribute):
$('[data-toggle="modal"]').on('click', function () {
const toggler = $(this);
const toggler_identifier = toggler.attr('data-toggler');
let modal_id = toggler.attr('data-target');
$(modal_id).find('.js-toggler__input').val(toggler_identifier);
});
so you can get the toggler by jQuery:
let toggler_identifier = $("#sendEmail").parents('.modal').find('.js-toggler__input').val();
console.log($('[data-toggler="' + toggler_identifier + '"]'))
be care about:
data-toggler attributes should be unique
some points:
better to use classes over data-attributes to select DOM, data-attributes should use to store little data.
Answer by Ali works, but you can try this too:
Add a hidden field in the modal: <input type="hidden" id="hidden-value">
On clicking the modal toggle, set the value of this hidden-value:
$('#open-modal').on('click', function(event) {
$('#hidden-value').val($(this).data('foo'));
});
On clicking the OK button, get the value (just logging here):
$( "#sendEmail" ).on('click', function() {
console.log($('#hidden-value').val());
});
This is an answer more on the way of 'set the value somewhere, then get it on click'.
You can try this instead assign foo to button data-attr
$('#emailFoo').on('show.bs.modal', function () {
const callerFromAnchorTag = $(e.relatedTarget);
const foo = callerFromAnchorTag [0].dataset['foo'];
$('#sendEmail').attr('data-foo', foo);
});
then
$('#sendEmail').click(function(){
const foo = $(this).data('foo');
});

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

Closing bootstrap modal

I have two buttons on modal, on first I need to save changes and close modal, on second I need to close modal and reset changes - same thing when person closes modal by clicking anywhere. The problem is I don't know how to check whether save button was clicked.
Here is html:
<div class="modal fade" id="modalNumber" tabindex="-1" role="dialog" aria-labelledby="modalNumberLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
blablabla
<div class="modal-footer">
<button data-dismiss="modal" class="btn-u btn-u-default" type="button">{{ 'backButton'|trans }}</button>
<button type="submit" class="btn-u saveChanges">{{ 'confirmChangesButton'|trans }}</button>
</div>
</div>
</div>
</div>
and here is JS code:
$('.saveChanges').on('click', function () {
// doing something here
// ....
// and closing modal in the end
$(this).closest('.modal.fade').modal('hide');;
});
$('.modal.fade').each(function(index, object) {
$(object).on('hidden.bs.modal', function (e) {
console.log(e.target);
// here is part of irrelevant code - what's important is that I use index and I need to know if saveButton was clicked
mainContainer.resetGroup(index);
});
});
e.target always returns div class="modal fade" element, not the button
What's important - I don't want to call mainContainer.resetGroup(index); when save button was clicked.
When you attach a function to your save-btn you don't need to know which button was clicked. In my example are two functions, similar to your example. The first function is called when the save-btn is clicked. In this function you can fetch the data, which you have to save and save it (e.g. via ajax).
The second method is called every time when the modal is closed. But when the save-btn was pressed, the first function was invoked before, and therefore you don't need to check any more which button was pressed...
You just need to replace the alert(data) function with your 'save procedure'. I hope that I didn't misunderstood your question...
$(document).ready(function(){
$('.save-btn').on('click', function(evt){
evt.preventDefault();
var $btn = $(this);
var $modal = $btn.closest('.modal');
var data = $modal.find('form').serializeArray();
// save data
alert(data);
// close modal
$modal.modal('hide');
});
$('#myModal').on('hidden.bs.modal', function(evt) {
alert('modal was hidden -- clear input fields');
$('#myModal').find('input').val('');
});
});
Check out this fiddle: https://jsfiddle.net/216q3jgk/4/
EDIT:
In the case that you would know which button was pressed, I would suggest to add a data-attribute to your modal, when the save-btn is pressed.
To add the data attribute call this in the first function before the modal is closed:
$modal.data('savePressed', true);
The data-attribute can be checked in the hidden.bs.modal function with the following code:
var $modal = $(evt.target);
if (!$modal.data('savePressed')) {
// save button was NOT pressed
alert('save not pressed');
}
You can find a full example in this fiddle: http://jsfiddle.net/216q3jgk/5/

Javascript load fresh form

I have a simple form which is opened within a modal when an anchor is clicked.
<a id="callbackLink" class="various" href="#inline">Request</a>
<div id="inline" style="display:none">
<form id="callForm" onsubmit="callEvent(event);">
<h3>Call Back</h3>
<label for="Number">What number shall we call you on?</label>
<input type="tel" id="callback-tel" placeholder=""><br>
<input type="submit" value="Submit" />
</form>
</div>
When the form is submitted, a third party library processes the form. If the form is successful, the form is removed and a success message is displayed in the modal.
Now if you close the modal and then click the button to display the form again, it will still show the success message. So I need a way of displaying a clean form every time the button is pressed.
What would be the best way to achieve this?
UPDATE
The event listener is
function StartClickToCall(event) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
var SuccessfulRequest = function() {
document.getElementById('ClickToCallForm').style.display = 'none';
document.getElementById('ClickToCallErrorMessage').style.display = 'none';
document.getElementById('ClickToCallSuccessMessage').style.display = 'block';
};
var FailedRequest = function(Request, Response) {
document.getElementById('ClickToCallSuccessMessage').style.display = 'none';
document.getElementById('ClickToCallErrorMessage').style.display = 'block';
document.getElementById('ClickToCallErrorMessage').innerHTML = Response.ResponseMessage;
};
_novero.push(['NoveroCallback', 'NewCallback', {
Destination : jQuery("#callback-tel").intlTelInput("getNumber"),
CallbackDate : document.getElementById('CallbackDate').value
}, SuccessfulRequest, FailedRequest]);
}
$('#myModal').modal('toggle');
$('#myModal').modal('view');U can try with modal window cleaning.I think modal window seems to be problem
you didnt post the correct part of the code
if the form is replaced by a success message, then you probably have a function that is making an ajax call and in the success callback you are removing the from HTML and put in the success message HTML
if so .. if you wan to restore the form on modal close . then you need to attach a function to close click that will remove the success message HTML and re-insert the Form HTML
EDIT:
$(".selector").fancybox({
onClosed: function() {
document.getElementById('ClickToCallForm').style.display = ‘block’;
document.getElementById('ClickToCallErrorMessage').style.display = ‘block’;
document.getElementById('ClickToCallSuccessMessage').style.display = ‘none’;
};
});
something like this . (you deleted the fancy declaration) . the close method might have a different name
but what is happening:
on fancy modal close . switch back the styles of the form . that are overwritten in the success function

colorbox close button with iframe

I am using colorbox for modal popup and the content of the popup is coming from a URL since this is displayed inside an iFrame how can I add a close button to the modal popup?
Thanks
This is the code for color box
<a class="Modal" href="http://google.com" onclick="openModal();">Click here</a>
And the js:
var openModal = function (){
$(".Modal").colorbox({
iframe:true,
opacity:0.5,
scrolling:true,
width:832,
height:456,
top:60
});
}
Try adding this to colorbox-iframe.html
<input type="button" name="btnClose" value="Close" onclick="parent.$.colorbox.close()" />
I've never used colorbox before, but maybe you want to add the close button via jQuery in your function:
var openModal = function (){
$(".Modal").colorbox({
iframe:true,
opacity:0.5,
scrolling:true,
width:832,
height:456,
top:60
});
$("<div class='thisClosesTheModal'>Close Modal</div>").appendTo(".Modal");
// style .thisClosesTheModal to look like a close box
}
// and then the function that closes the modal
$(".thisClosesTheModal").live('click', function(){
$('Modal').hide();
}

Categories

Resources