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

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 );

Related

Javascript handle condition before form is submitted

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();
}
});

jquery seems not to work inside bootstrap 4 popover

I want to send data via jquery (jquery-3.2.1.min.js) and ajax from inside of a bootstrap popover.
The popover works fine, but I cannot get the submit to work.
I initialized the popover with
$(document).ready(function() {
$(function(){
$("[data-toggle=popover]").popover({
html : true,
content: function() {
var content = $(this).attr("data-popover-content");
return $(content).children(".popover-body").html();
},
title: function() {
var title = $(this).attr("data-popover-content");
return $(title).children(".popover-heading").html();
}
});
});
});
This is the html trigger:
<span tabindex="0" role="button" data-toggle="popover" data-placement="right" data-popover-content="#comment230" data-original-title="" title="">
<img src="/ds/img/comment.svg" alt="comment" height="16px">
</span>
And this is the html inside the popover:
<div id="comment225" style="display:none;">
<div class="popover-heading">Comments</div>
<div class="popover-body">
<div class="commentbody">
<div>
<fieldset>
<div class="input text">
<label for="comment">Comment</label>
<input name="comment" id="comment" type="text" />
</div>
</fieldset>
<button class="submittest" id="acomment225button">Test</button>
</div>
</div>
</div>
</div>
For testing reasons I did this:
$(".submittest").click(function(e) {
alert('test');
e.preventDefault();
});
The alert does not work from buttons inside the popover, but from buttons placed on the rest of the page.
How can I get this to work?
Those DOM elements are not present at the time you are subscribing to the event.
You need to hook up to events in this fashion:
$(document).on("click", ".submittest", function(e){
alert("test");
});

jquery script doesn't work for me

$('a.locked').click(function(e) {
e.preventDefault();
});
$(document).ready(function(){
$("button.button2").click(function(){
$("a").removeClass("locked");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com"target="_blank" id="action2">
<button class="button2">
<span class="icon">CLICK HERE</span>
</button>
<br>
<br>
</a>
<a href="example.com"class="locked">
<button class="locked-button">
<i class="fa fa-lock" aria-hidden="true"></i>
<span class="icon">CONTINUE</span>
</button>
</a>
I want that the last a element is locked, and if you click on the 2nd button, the class locked will be removed from the last a element and I will be able to click on the link.
It deletes the class but I still can't click the link. How to fix that?
Also, is there are smarter way to do that...
This event binding isn't removed from the <a> when its class="locked" is removed:
$('a.locked').click(function(e) {
e.preventDefault();
});
At least with direct bindings like this, jQuery only uses the selector initially to attach the event handler to all matching elements. It won't recheck the selector when the event is later triggered. Currently, you'll have to do that check yourself:
$('a').click(function (e) {
if ($(this).hasClass('locked')) {
e.preventDefault();
}
});
Though, if you have an overall parent element, you can use a delegated binding and jQuery will then recheck the (2nd) selector for you when the event is triggered.
<div id="parent">
<a href="example.com" target="_blank" id="action2">
<!-- ... -->
</a>
<a href="example.com" class="locked">
<!-- ... -->
</a>
</div>
$('#parent').on('click', 'a.locked', function (e) {
e.preventDefault();
});
So, just removing a css class will not work in your case.
You should remove the event handler to allow the button to be clicked, something like this should work:
$("a.locked").on("click.locked", function(e) {
e.preventDefault();
});
$(document).ready(function(){
$("button.button2").click(function(){
$("a.locked").off("click.locked");
$("a").removeClass("locked");
});
});
Working jsfiddle.
Like this?
Check out this SO question to read more about the toggle function I used.
$(document).on("click", "#ToggleLock", function(e) {
$('#Continue').prop('disabled', function(i, v) {
return !v;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id='ToggleLock'>Unlock/Lock</button>
<button onclick="location.href='http://www.example.com'" type="button" id='Continue' disabled>Continue</button>
Let me know if I have greatly misunderstood the question.
Remove the class is not enough, since you added a click event to all $('a.locked') you need use .off() to remove the click event after removing the class. Also try to target the specific element, you could add id="btn_continue" to 2nd button. ($("a") will target all <a> which is not what you want to do)
Note:
$('a.locked').click(function(e) {
e.preventDefault();
});
$(document).ready(function(){
$("button.button2").click(function(){
$("#btn_continue").off().removeClass("locked");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com" target="_blank" id="action2">
<button class="button2">
<span class="icon">CLICK HERE</span>
</button>
<br>
<br>
</a>
<a href="example.com" id="btn_continue" class="locked">
<button class="locked-button">
<i class="fa fa-lock" aria-hidden="true"></i>
<span class="icon">CONTINUE</span>
</button>
</a>

Javascript click function only work once

I have a dropdown menu with a submit function that executes, if any children from the dropdown is clicked.
Now I want to prevent the submit function to a special li element, because there should be insert a tracking id in a popup iFrame.
With the following code it works so far on the first dropdown menu and prevent the submit function, but it wont work on all following dropdown's.
Maybe someone has a short solution for me?
<script type="text/javascript">
$(document).ready(function() {
$('.track').click(function(){
stopPropagation();
});
$('.dropdown li').click(function() {
document.getElementById('opt').value = $(this).data('value');
$('#options').submit();
});
$("#options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
});
</script>
<form name="" action="" method="post" id="options">
<input type="hidden" name="update" id="opt" value="">
<div id="item-select-option">
<div class="dropdown">
Options <span class="caret"></span>
<ul id="selector" class="dropdown-menu pull-right" role="menu">
<li data-value="paid">paid</li>
<li data-value="shipped">shipped</li>
<li class="track">track</li>
</ul>
</div>
</div>
</form>
Problem: You've several elements with the id track/options when the id attribute should be unique in same document, so when you attach event to the id just the first element with this id that will be attached.
Suggested solution :
Use class instead of id's, like :
<form name="" action="" method="post" class="options">
.....
<li class="track">
track
</li>
</form>
Then you js should be like :
$('.track').click(function(event){
event.stopPropagation();
});
$(".options").submit(function() {
if (confirm('are you sure?')){
return true;
} else {
return false;
}
});
NOTE : The event should be present in anonymous function function(event).
Hope this helps.

I'm trying to implement a click event on a bootstrap dropdown menu

Hi I have a bootstrap dropdown menu that is auto filled from a database. I am trying to get an event to happen when I click on one of the items in the menu. I have tried
$("body").on("click", ".ddBtnClick", function(event) {
console.log("Is it working? Yes!!");
});
with ".ddBtnClick" being a class assigned to each of the items in the list. but nothing happened.
Here is the code to populate the list from a database.
$.getJSON("http://jeremiah.abrahamott.com/DadsCarsObjects.txt", function(data){
$.each(data.aaData, function(i, option){
$("#dropdownfill").append($('<li/>').append($('<a/>').attr("id", option.Year).attr("href", "#").attr("tabindex", "-1").addClass("ddBntClick").text(option.Make)))
});
});
Here is the html for the dropdown.
<div class="row" style="margin-left:50px;">
<div class="span3">
<div class="btn-group">
<a class="btn dropdown-toggle" data- toggle="dropdown" href="#">Make
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu" id="dropdownfill">
</ul>
</div>
</div>
</div>
Issue is with your className. You are registering the delegated event handler for ddBtnClick but actual class name is ddBntClick.
$("body").on("click", ".ddBtnClick", function(event) {
console.log("Is it working? Yes!!");
});
and
.addClass("ddBntClick");
Change the class name during construction or change in your event delegation.
$(function()
{
$("body").on("click", ".ddBntClick", function(event) {
console.log("Is it working? Yes!!");
});
});
Have you tried wrapping your Javascript in the document.ready event?
$(function()
{
$("body").on("click", ".ddBtnClick", function(event) {
console.log("Is it working? Yes!!");
});
});
See the jQuery .ready() documentation for more information and examples.
Also, you should register the click event on the actual button and use .click() instead of .on():
$(function()
{
$(".ddBtnClick").click(function(event) {
console.log("Is it working? Yes!!");
});
});
Also, you have a typo:
.addClass("ddBntClick")
Should be:
.addClass("ddBtnClick")

Categories

Resources