Javascript handle condition before form is submitted - javascript

I need to submit a form based on a condition. If true send the form via a modal or simply submit the form directly. What happens is that even when the condition is true the form is sent anyways without waiting that the click on the modal is triggered. After my research I understood that there was a way to prevent the submit with e.preventDefault();. I haven't been able to get the result I want since it just did stop the execution.
(function($) {
$(document).ready(function() {
$( "#save" ).click(function(e) {
if (selectedValIndConstitutionCan === 'waiting'){
$("#form").on('submit', function(e){
e.preventDefault();
});
$('#popupConfirmationEnregistrement').modal("show");
}
$("#confirmYesButtonModal").click(function() {
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
showProgress();
});
showProgress();
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
});
selectDeselectRadioButtons();
});
})(jQuery);
HTML and JSP
<%# include file="/WEB-INF/pages/include/include.jsp" %>
<script src="${contextpath}/js/inputMask/jquery.mask.min.js"></script>
<script type="text/javascript">
</script>
<form:form id="form" modelAttribute="formSaving" action="#">
<fwd:csrfToken />
<div class="row form-group boutons-margin-top">
<div class="col-xs-offset-12 col-xs-12 control-label text-left">
<button class="btn btn-primary" type="button" id="save" data-toggle="modal" data-target="#modalSave">
<spring:message code="xxx.save"/>
</button>
</div>
</div>
</div>
</div>
</c:otherwise>
</c:choose>
</form:form>
<div id="modalSave" class="modal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body">
<spring:message code="msg"/>
</div>
<div class="modal-footer">
<button id="confirmNo" class="btn btn-default" data-dismiss="modal"><spring:message code="no"/></button>
<button id="confirmYesButtonModal" class="btn btn-primary" data-dismiss="modal"><spring:message code="yes"/></button>
</div>
</div>
</div>
</div>

If you click 'save' button, its will submit it anyway in here.
showProgress();
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
I'm not sure why, but if what you want submit it when selectedValIndConstitutionCan is not 'waiting', use else.
(function($) {
$(document).ready(function() {
$( "#save" ).click(function(e) {
if (selectedValIndConstitutionCan === 'waiting'){
$("#form").on('submit', function(e){
e.preventDefault();
});
$('#popupConfirmationEnregistrement').modal("show");
}else{
showProgress();
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
}
$("#confirmYesButtonModal").click(function() {
$("#form").attr(
'action',
CONTEXTE +
'/formsave/save');
$("#form").submit();
showProgress();
});
});
selectDeselectRadioButtons();
});
})(jQuery);

So finally it is working I had indeed to put the logic in the else clause in case no waiting value is selected AND put the radiobuttons definition variable inside the save on click event
$( "#enregistrer" ).click(function() {
var selectedValIndConstitutionCan = $("[name='infoFiscale.indConstitutionCanada']:checked").val();
if (selectedValIndConstitutionCan === 'waiting'){
$("#popupConfirmationEnregistrement").modal("show");
$('#confirmationEnregistrerOui').on('click', function() {
$("#declarationImpot").attr(
'action',
CHEMIN_CONTEXTE +
'/declarationImpot/enregistrer');
$("#declarationImpot").submit();
affichePopupVeuillezPatienterModaleGenerique();
});
} else {
affichePopupVeuillezPatienterModaleGenerique();
$("#declarationImpot").attr(
'action',
CHEMIN_CONTEXTE +
'/declarationImpot/enregistrer');
$("#declarationImpot").submit();
}
});

Related

AJAX call not triggered on show.bs.modal

I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})

How get clicked id when clicked element in modal window?

I am beginner web developer.
I have code to dynamic load data to iframe:
$(document).ready(function () {
function loadMaterials(type, query) {
$.ajax({
type: 'GET',
url: '/getMaterials',
dataType: "text",
data: {
query: query,
type: type,
},
success: function (data) {
$('.dynamic-materials').html(data);
}
});
}
$('.product-material-front').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(2, "");
$('.select-material-title').html('MateriaĹ frontu')
$('.material-type-input').val(2);
$('#material-dialog-modal').modal('show');
});
$('.product-material-body').on('show.bs.select', function () {
$('.product-query-string-body').val('');
loadMaterials(1, "");
$('.select-material-title').html('MateriaĹ korpusu');
$('.material-type-input').val(1);
$('#material-dialog-modal').modal('show');
});
});
<div id="material-dialog-modal" 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>
</div>
<div class="modal-body pt-0">
<h3 class="select-material-title px-3"></h3>
<form method="get" action="{{ route('frontend.get.materials') }}" class="px-3 select-material-url">
<input type="hidden" name="type" value="" class="material-type-input">
<div class="inner-addon rounded-0 modal-search-form">
<i class="fa fa-search"></i>
<input type="text" class="form-control product-query-string-body"
placeholder="Szukaj produktu"
aria-label="Wpisz nazwę lub kod koloru"/>
</div>
</form>
<div class="row material-list px-5 pt-4 dynamic-materials">
</div>
</div>
</div>
</div>
</div>
It's work fine.
I need to change the classes of the clicked elements.
Additionally, I want to select select with the option selected.
I made a code like this:
$('.select-material-body').on('click', function(e){ console.log('ok');
if($('.material-type-input').val() == 1){
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-body]').val($(this).attr('id'));
$('.product-material-body').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
} else{
$(".select-material").removeClass("selected-material");
$(this).addClass("selected-material");
$('select[name=product-material-front]').val($(this).attr('id'));
$('.product-material-front').selectpicker('refresh');
$('#material-dialog-modal').modal('hide');
}
});
But unfortunately it doesn't work :(
How can i repair it?
My preview: http://serwer1356363.home.pl/_nauka/ - popup is visible after click select (with icon)
Please help me..
Since the modal content isn't append on the document, you can't bind event to it.
Instead, you can add an on() event to the body, passing your sub-selector :
$('body').on('click', '.select-material-body', function(e) { console.log('ok'); });

How to create a click-function in a modal

Hey I am new to js and I was trying to open a bootstrap modal with a click on a button (I set the id to the value of the button because the id comes from a database) and if you click on "yes" in that modal a click function should be triggered which should then delete the selected row.
I am able to open the modal and setting the id also works but if I click the yes button in the modal there is no alert...
This is the modal located in content.html:
<!--Delete Modal-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Return Device</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<p><b> Are you sure you want to return this device? </b></p>
Please make sure you return the device.
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary delBtn" data-dismiss="modal">Yes</button>
</div>
</div>
</div>
</div>
This is my JS located in main.js:
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').trigger('focus');
});
$('#booked').click(function () {
$('#changestuff').load('content.html #booked', function () {
register();
change();
$('.ret').click(function () {
var id = $(this).val();
var tr = $(this).closest('tr');
})
returnOne(id, tr);
});
$('#booked').addClass('active');
$('#book').removeClass('active');
$('#admin').removeClass('active');
});
});
function returnOne(id, tr)
{
$('.delBtn').click(function () {
alert("you returned" +id);
})
}
Where is my error? I think it might be because the modal hasn't been loaded when I try to get the click event but I'm not sure. Thanks in advance!
click event handler is not attaching may be it is getting called before yes button dom get created.
Try below code where you can store row to be deleted in a variable and set row-id data attribute on Yes button. In click handler of Yes button, read the id and you can delete row from variable rowToDelete
$(document).ready(function(){
var rowToDelete;
$('#myModal').on('shown.bs.modal', function(){
$('#myInput').trigger('focus');
});
/*$('#changestuff').load('content.html #book', function(){
register();
change();
getChosenDevices();
});*/
$('#changestuff').on('load','content.html #book', function(){
register();
change();
getChosenDevices();
});
$('#booked').click(function() {
$('#booked').addClass('active');
$('#book').removeClass('active');
$('#admin').removeClass('active');
});
$(document).on('click','.ret',function() {
var id = $(this).val();
$('#deleteModal .delBtn').data('row-id', id); //set data id
rowToDelete = $(this).closest('tr'); //store row in variable
});
$(document).on("click", '#deleteModal button.delBtn', function(e) {
e.preventDefault();
var rowId = $(this).data('row-id');
alert("you returned" + rowId);
$('#deleteModal').modal('toggle');
});
});
JSFiddle Demo

Submit confirmation via Bootstrap Modal

I wanted to have a Submit Modal Confirmation But I have failed to do it correctly.
Here is my JS:
function warning(){
$('#ModalSubmitCart').modal('show');
var yes = document.getElementById('confirm').value;
if (yes == 'yes') {
return true;
}
else {
return false;
}
}
part of my modal:
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="confirm" value="yes">Yes</button>
</div>
my form
<form onSubmit="return warning()" method="POST" action="submitcart.php">
I wanted to have something like confirm() but in a Modal form.
There is no direct callback functions for the bootstrap modal.
I have done a slight hack here.
What I have done:
Added a class to both the buttons on the modal.
Attached a click callback handler for the buttons & verify by the textof the button whether a close button is or yes button .
JS Code:
$(function () {
$('#show').on('click', function () {
console.log('clicked');
warning();
});
$('.buttons').on('click', function () {
var yes = $(this).text();
if (yes === 'Yes') {
console.log('yes');
//return true;
} else {
console.log('close');
//return false;
}
});
});
function warning() {
$('#ModalSubmitCart').modal('show', function (data) {
console.log('data:' + data);
});
}
Live Demo # JSFiddle:http://jsfiddle.net/dreamweiver/wccqyzej/
You can wrap your modal in a FORM and use a submit button, as you're doing.
<form action="/echo/html/" method="POST" name="modalForm" id="modalForm">
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content panel-warning">
<div class="modal-header panel-heading">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
...
</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>
</div>
</form>
and use jQuery to intercept the submit event.
$('#modalForm').on('submit', function(e){
if (!confirm('are you sure?'))
{
e.preventDefault();
return false;
}
});
You can see how it works in this fiddle.
I think you should use this way your jquery code
function warning(){
$('#ModalSubmitCart').modal('show');
var yes = $('#confirm').attr("value");
if (yes == 'yes') {
return true;
}
else {
return false;
}
}

event.preventDefault() doesn't work with button?

Why is it .preventDefault() doesn't work or even alert() on my form?
<div id="popover-head" class="hide">Add new tab</div>
<div id="popover-content" class="hide">
<form class="form-inline" id="myForm" method="POST" action="../admin/FLT_add_tab.do">
<div class="form-group">
<!-- my form -->
<input type="text" name="newTab"/>
<button class="btn btn-primary" type="submit" ><i class="icon-white icon-ok"></i></button>
<button class="btn" type="button" onClick="popRemove();" ><i class="icon-remove"></i></button>
</div>
</form>
</div>
The JS code:
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
alert("Thank you for your comment!" + e);
e.preventDefault();
});
});
I don't know what am I doing wrong.
UPDATE:
link that has the popover:
<li><i class="icon-plus-sign"></i> Tab</li>
JS that trigger the popover"
$('#popover').popover({
html : true,
title: function() {
return $("#popover-head").html();
},
content: function() {
return $("#popover-content").html();
}
});
jsfiddle: http://jsfiddle.net/9uYuH/
since popover in bootstrap is dynamically generated, you should use the following jquery function
$(document).on('submit','#myform', function(e) {
alert("Thank you for your comment!" + e);
e.preventDefault();
});
Use .on()
As popover in bootstrap generated dynamic elements you can not bind events directly to them .So you have to use Event Delegation.
$(document).on('submit','#myform', function(e) {
alert("Thank you for your comment!" + e);
e.preventDefault();
});
or Better use
$('#popover').on('submit','#myform', function(e) {
alert("Thank you for your comment!" + e);
e.preventDefault();
});
Syntax
$( elements ).on( events, selector, data, handler );

Categories

Resources