jquery modal() not working when called from inside a function - javascript

I have a table where i put a button on the final column of some rows. This button is supposed to open a bootstrap modal using jquery through the onclick attribute. It calls a js function which has the jquery method that shows the modal, but is not working.
When I put an alert on the function and comment the jquery method it works. Also, when I call the method to open it outside of any function, it works when I load the page, as it should. So for some reason it only doesn't work when I try to call it from inside a function.
I need to call it from inside the function because I need to pass some values from the specific table row.
Button:
<button type="button" class="btn btn-success btn-sm" onclick="iniciar_produccion();">Iniciar Producción</button>
Jquery:
// This works
$("#modalIniciarProduccion").modal();
function iniciar_produccion() {
// This doesn't work
$("#modalIniciarProduccion").modal();
// alert('working');
}
Modal:
<div id="modalIniciarProduccion" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Finalizar Proyecto</h4>
</div>
<div class="modal-body">
<form action="marcar_proyecto_como_finalizado.php" id="finalizar" method="post" target="_self">
<div class="input-group">
<label> Fecha en que se entregó </label>
<input type="date" id="fechaEntrega" name="fechaEntrega" class="form-control" required>
<br><br>
</div>
</form>
</div>
<div class="modal-footer">
<input type="submit" form="finalizar" class="btn btn-default pull-right" name="action" value="Subir">
</div>
</div>
</div>
</div>
Your help is much appreciated

You put the wrong function name in the HTML.
Your function is called modalIniciar_produccion but you wrote onclick="iniciar_produccion();"
To be safe please copy&paste your function name from JS code into the HTML (note hat JS is also case dependent).

Upon further research I tracked the error the console gave me and found the solution to my problem in other post:
Bootstrap modal: is not a function
So this is a duplicate. Please mark it as such.
Anyway, the problem was conflict of the jQuery version being loaded twice. The solution is the following:
function iniciar_produccion() {
jQuery.noConflict(); // I added this
$("#modalIniciarProduccion").modal(); // This was not working
}
I just added the line jQuery.noConflict(); before the jquery method. Hope this helps someone in the future.

Related

jQuery onclick registration error

I have a button that I want to attach a click listener to, but everytime the code runs, it throws a console error
jquery.js:4435 Uncaught TypeError: ((n.event.special[g.origType] || (intermediate value)).handle || g.handler).apply is not a function
Here's the js code that triggers the error, the first line runs fine, the second line is the one that causes the error
$toolbar.off('click', '.btn-save'); // $toolbar is assigned $("#toolbar") on init
$toolbar.on('click', '.btn-save', function(e){
saveData(0);
});
What confuses me is, if I run that bit of code manually through the console, I get no errors
Here's the HTML
<div class="row" id="toolbar">
<div class="col-lg-12">
<button type="button" class="btn btn-primary btn-save">Save</button>
<button type="button" id="btnCancel" class="btn btn-default btn-cancel">Cancel</button>
</div>
</div>
I have found the problem, below my listeners, there's an unrelated listener that I attached
$(document).on("click", "#btn-back", Views.Editor.close);
The problem here is that Views.Editor.close is the wrong method name.
When I changed the method name, the error disappears
I didn't realize that an unrelated listener can affect others
Ah. looks like you may have your JQuery params wrong if I've understood the question/ what you're trying to do.
DOM events should be appended to items on
html:
<div class="row">
<div class="col-lg-12">
<button id="save-btn-id" type="button" class="btn btn-primary btn-save">Save</button>
<button type="button" id="btnCancel" class="btn btn-default btn-cancel">Cancel</button>
</div>
</div>
js:
$(document).ready(function() {
$('#save-btn-id').click(function(evt) {
saveData(0);
});
});
From what I see at jQuery's API docs for their .off() function & in the code example above, it looks like the function isn't being passed as the 3rd parameter to the .off() function. So it's possible that the jQuery library is complaining that it can't find a function to remove it.
See: http://api.jquery.com/off/
Try this & see if it helps:
function clickListener(e){
saveData(0);
};
$toolbar.off('click', '.btn-save', clickListener);
$toolbar.on('click', '.btn-save', clickListener);
Try this: https://jsfiddle.net/jorge182/a1y9abcj/2/
toolbar = $("#toolbar")
$(toolbar).off('click', '.btn-save'); // $toolbar is assigned $("#toolbar") on init
$(toolbar).on('click', '.btn-save', function(e){
saveData();
});
function saveData(){
alert();
}

How to reload a page on Submit

I have a Bootstrap Modal which contains a form. The Modal also contains a Submit and Cancel Button. The cancel button is working fine and it is closing the Modal successfully. Now as per my requirement on Submit Button Click of the Modal the Form is Submitting Successfully by passing the User inputs to Web Service but Modal is not getting closed. Also I need to reload the page on Submit button click event only. Here is my HTML..
<div class="modal fade" id="StudentModal" tabindex="-1" role="dialog" aria-labelledby="StudentModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<form action="~/GetStudent" class="form-horizontal" role="form" method="post" id="frmStudent">
<div class="modal-footer">
<div class="pull-right">
<button type="submit" class="btn btn-success"><i class="glyphicon glyphicon-ok"></i> Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="glyphicon glyphicon-remove"></i> Close</button>
</div>
</div>
</form>
</div>
I tried following ways to close the Modal ..
$('#frmStudent').submit(function() {
$('#StudentModal').modal('hide');
return false;
});
As per my Requirement I need to close the Modal on Submit event and reload the page after getting back from Web Service. How can I do this with Jquery?
Note: I am not supposed to use Ajax Call here ..I need to submit form from form action only
This HTML will not work:
<form onsubmit="window.location.reload();">
But this HTML does the job:
<form onsubmit="setTimeout(function(){window.location.reload();},10);">
So the browser has enough time to submit the form and then reload the page ;-)
after submitting your form you can just make this call via javascript:
window.location.reload();
If you want the page to reload when you submit a form, use the onsubmit event handler:
document.getElementById("frmStudent").onsubmit = function(){
location.reload(true);
}
This code should reload the page, submit your form, and close the modal.

Open Django template in bootstrap Modal

I'm trying to open a Django template in Twitter-Bootstrap Modal. Earlier I did it using JavaScript but it only opened once.
I read somewhere that Bootstrap Modals are more customizable, so giving it a try, I referred to an already answered question. I've the same problem and I've tried the same solution but it doesn't work for me. The only thing I get is blackened screen.
The flow goes like this:
A Django template is rendered which has several worker's details.
In that template, I've links to "Add advance" for every worker.
Clicking on which I want to open Modal.
In that Modal, I want to open another Django template containing a
form.
Filling the form, either close or press enter.
For any of these events on Modal, save the data from the form.
What I've done is here:
Template where the link is clicked: form.html
<a class="contact" href="#" data-form="/popupadvance/?worker_id={{value.worker_id}}&year={{year}}&month={{month}}" title="Advance"> Add advance</a>
<div class="modal hide" id="contactModal">
<script>
$(".contact").click(function(ev) { // for each edit contact url
ev.preventDefault(); // prevent navigation
var url = $(this).data("form"); // get the contact form url
alert(url);
$("#contactModal").load(url, function() { // load the url into the modal
$(this).modal('show'); // display the modal on url load
});
return false; // prevent the click propagation
})
</script>
The template which should open: popup.html
<div class="modal hide" id="contactModal">
<form id="form" class="well contact-form" action='/popupadvance/?worker_id={{value.worker_id}}&year={{year}}&month={{month}}' >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
{% csrf_token %}
{{worker_id}} <br />
{% for a in old_advances %}
{{a.advance_amount}} {{a.advance_date}}<br />
{% endfor %}
<input type="integer" id="popupadvance_{{worker_id}}" placeholder="Advance ++" class="popupadvance" >
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save" />
<input name="cancel" class="btn" type="submit" value="Cancel"/>
</div>
</form>
Clicking on the link: "Add advance", the only thing I get is the alert I've added closing which I get blackened screen over which the Modal should appear but neither the Modal, nor the form is rendered there. But pressing forward button on browser, I get the popup.html rendered on a new page, which probably tells that the URL is working on clicking the link, but only the Modal doesn't open.
I would like to tell that the input field in pupup.html is able to save data to database with OnChange event as I did when I opened up the dialog box using JavaScript.
Any help to find the problem will be greatly appreciated. As I don't see any error on Browser console.
Thanks.

Meteor view doesn't get updated on IE

In my application which is using MeteorJS I have a situation when I have to subscribe to "multiple aspects" of a single collection.
I have a collection called Invitations, and on the main page, I subscribe to a publication which publishes those Invitations, where the InvitedUser is the current user.
Then on a modal dialog, I want to manage those Invitations which are sent by the current user. I don't want to subscribe to the changes of the sent Invitations only on this dialog.
So I decided to manually subscribe to a publication when the dialog is shown to the user and stop this subscription when the modal gets closed.
The code behind for the modal dialog looks something like this:
var subscriptionHandle;
Template.invitationsModal.helpers({
invitations: function() {
var activeGroupId = Session.get('activeGroupId');
var filter = activeGroupId ? {invitedBy: Meteor.user()._id, group: activeGroupId} : {};
return Invitations.find(filter);
}
});
Template.invitationsModal.rendered = function() {
$('#invitationsModal').off('shown.bs.modal').on('shown.bs.modal', function(e) {
var activeGroupId = Session.get('activeGroupId');
subscriptionHandle = Meteor.subscribe('sentInvitations', activeGroupId);
});
$('#invitationsModal').off('hidden.bs.modal').on('hidden.bs.modal', function(e) {
subscriptionHandle.stop();
});
};
(I left out the unimportant parts.)
In the template I just iterate through the invitations helper:
<template name="invitationsModal">
<div id="invitationsModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form role="form" class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Invitations</h4>
</div>
<div class="modal-body container-fluid">
{{#each invitations}}
{{> invitationRow}}
{{/each}}
<div class="form-group">
<div class="col-xs-offset-2 col-xs-6">
<input type="text" class="form-control" name="name" placeholder="Name or email">
</div>
<div class="col-xs-2">
<input type="submit" class="btn btn-default button-add" value="Invite" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</template>
This template then included in my main page:
{{> invitationsModal}}
When I first load the page, the Session variable activeGroupId is empty, so wrong data is loaded into the hidden modal.
When I show the modal to the user, I set the activeGroupId to some value, so:
the invitations helper is executed again because of this change, and now we return the valid list of invitations for the active group.
the DOM is updated inside the modal to reflect the change in the 1.)
Now here comes the interesting part: the whole solution works fine on Chrome and Firefox but not always on IE.
On IE there is one case when the 1.) step runs correctly, but the 2.) is simply not executed.
This is the case when I open the modal for the first time. This time the DOM contains the wrong, unfiltered collection.
When I close and open the modal for the second time (without refreshing the page in the browser), it works fine again.
I don't have any idea what could cause this behavior. Could it be a bug in Meteor, or so?
(Tested in IE11)
A call to Deps.flush() magically solved the issue - this is the event handler which shows the dialog to the user:
'click .menu-command-invitations': function(e) {
Session.set('activeGroupId', this._id);
Deps.flush(); // without this, it won't work in IE
$('#invitationsModal').modal('show');
e.preventDefault();
}
From Meteor docs:
Deps.flush forces all of the pending reactive updates to complete.
For example, if an event handler changes a Session variable that will
cause part of the user interface to rerender, the handler can call
flush to perform the rerender immediately and then access the
resulting DOM.
Although I don't really know why I need to call this and why it didn't work only under IE.
I'm reading and writing session variables inside other event handlers in the same application and those work perfectly in IE.

jQuery Datepicker in Twitter Bootstrap 3 Modal

I have been trying quite a few solutions to this problem now but i can't get it to work.
I trying to get a datepicker into my form. The form is placed inside a bootstrap modal and thw whole thing is loaded via ajax. Everything works fine except the datepicker that does not show at all when placed in the modal.
I was hoping that a simple solution like: .datepicker {z-index:9999 !important;} would work, but it does not. Does anybody know a simple solution for this?
Here is my datepicker:
$(function() {
$( ".datepicker" ).datepicker({ dateFormat: "yyyy-mm-dd" });
});
Here is my form:
<form action="" method="post">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Endre artikkel</h4>
</div>
<div class="modal-body">
<label for="arrived">Motatt</label>
<input type="text" name="arrived" class="form-control datepicker" id="arrived">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</form>
The form is loaded into this div:
<div class="modal fade" id="load_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="z-index: 1040;"></div>
With this javascript:
function edit_article(id){
$("#load_modal").load("load_modal.cgi?type=edit&id="+id);
}
The modal is probably being loaded after you add the .datepicker() you should evaluate that code after loading the form.
function edit_article(id){
$("#load_modal").load("load_modal.cgi?type=edit&id="+id);
$("#load_modal .datepicker").datepicker({ dateFormat: "yyyy-mm-dd" });
}
If you call this code on the document ready()
$(function() {
$( ".datepicker" ).datepicker({ dateFormat: "yyyy-mm-dd" });
});
There is no form with datepicker so it isn't initialized
call this once more after loading form.
this shoudl fix your problem
$(function() {
$( "#arrived" ).datepicker({ dateFormat: "yyyy-mm-dd" });
});
I think that you are doing this mistake....
kindly look at this link http://jsfiddle.net/TB8Yt/
It sounds like I'm having exactly the same problem. I have a datepicker in my modal, and the datepicker works fine the first time my screen opens, but the second time nothing happens when you click the date field, and any further opens of the modal the date picker no longer works. I haven't looked too deeply into this code, but it seems that the date picker code must look for when it has the datepicker ui object on, and then no longer runs.
To solve this I run this when I open my modal:
$("#modal").on('hidden.bs.modal', function() {
$('#ui-datepicker-div').remove();
});
My date picker now works fine. This ui-datepicker-div is the one that datepicker automatically creates when you run $( ".datepicker" ).datepicker();

Categories

Resources