jQuery button click registering previous clicks - javascript

I have a form with multiple buttons that submit to it that differ by value. After I click a button, and then click a second button, the function operates on them both instead of just the second button. Is there a way to prevent this behavior?
This is somewhat related to a question I asked here: Why does function only work on second click? but the solution isn't valid if there a multiple buttons as it just registers the first button from the list of buttons.
JS:
$(document).ready(function () {
$(':button').click(function (){
var myval = $(this).attr("value");
$('#post-form').on('submit', function(event) {
event.preventDefault();
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
});
function create_post(btnval) {
console.log("create post is working!");
$.ajax({
HTML:
<form action="/create_post/" method="POST" id="post-form">
<div class="col-sm-4" id="toprow">
<h4 style="font-family:verdana"> Models </h4>
<img src='{% static 'images/USAcomplete2.png' %}' class="img-responsive thumbnail" id='gbimg' >
<div class="btn-toolbar">
<button type="submit" name="model" value="test" class="btn btn-default">test</button>
<button type="submit" name="model" value="test2" class="btn btn-default">test2</button>
<button type="submit" name="model" value="test3" class="btn btn-default">test3</button>
</div>
</div>
</form>

You need to prevent the form from submitting before the user clicks the button.
$(document).ready(function () {
$('#post-form').on('submit', function(event, myval) {
event.preventDefault();
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});
$(':button').click(function (){
var myval = $(this).attr("value");
$('#post-form').trigger('submit', myval);
});
Update
Sorry, I think this code should work. The above code would run twice, since a button click would be considered a form submit as well.
$(document).ready(function () {
$('#post-form').on('submit', function(event) {
event.preventDefault();
});
$(':button').click(function (){
var myval = $(this).attr("value");
console.log("form submitted!");
console.log(myval);
//var cbtn = $("button");
//var btnval = cbtn.val();
//console.log(cbtn);
document.getElementById('gbimg').style.display = 'none';
document.getElementById('rgimg').style.display = 'none';
create_post(myval);
});

What is happening here is that you are binding the submit event to #post-form a second time when a second button is clicked, as the binding happens inside the button clicking event callback.
The best way to prevent this is to move this
$('#post-form').on('submit', function(event) {
...
});
outside of your button click event.

Related

Delay Button Submit Javascript

I'm trying to add adelay on my submit button in javascript.
But it just seems to freeze and no longer commits any action after clicking on it.
Does anyone have an explanation ?
function Progress() {
var button = document.getElementById("Button");
var form = document.getElementById("new_video")
form.onsubmit = function() {
return false;
}
button.onclick = function() {
setTimeout(function() {
form.submit();
}, 2000);
return false;
}
}
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" onclick="Progress()" id="Button" data-disable-with="Upload" disabled="">
// Cache your Form Elements
const EL_form = document.querySelector("#myForm");
const EL_formSubmitBtn = EL_form.querySelector("#Button");
const Progress = (evt) => {
evt.preventDefault(); // Prevent Browser Submit action
EL_formSubmitBtn.disabled = true; // Disable the submit button
setTimeout(function() {
EL_form.submit(); // Or do AJAX stuff here
EL_formSubmitBtn.disabled = false; // Enable the submit button
}, 2000);
};
// Use Element.addEventListener instead of inline JS
// Don't attach handlers to button, rather use the Form "submit" Event:
EL_form.addEventListener("submit", Progress);
<form id="myForm" action="demo.php">
<input id="Button" type="submit" value="Upload" class="btn btn btn-primary">
</form>
PS: Don't capitalise names of regular functions that do not actually return an Object - or are not a Class by definition, use rather progress as your function name. Or rather be more descriptive, it's actually a formSubmitHandler
You could try this:
var button = document.getElementById("Button");
var form = document.getElementById("new_video");
button.onclick = function(event) {
event.preventDefault();
setTimeout(form.submit, 2000);
}
and
<input type="submit" name="commit" value="Upload" class="btn btn btn-primary" id="Button" data-disable-with="Upload">
Hope this helps.

Cannot cancel form submission in jquery

I am trying to cancel form submission after button click.
When button is clicked i get some information from check-timetable-timing-conflict with json.
So i decide to cancel the form submission if the data coming with json is 1.
But it does not cancel form submission although i get 1.
<form role="form" method="POST" id="subform" name="subform">
...
...
<button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course();">{% trans "EKLE" %}</button>
...
...
<script>
conflict = 0;
var select_course = function()
{
//alert("button clicked");
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
}
});
}
</script>
In order to prevent the form from submitting you need to return false from the onclick function that is called when the button is clicked. Also to prevent ajax form submissions you can also add e.preventDefault(); like below.
Note: The same effect could be achieved if using the form's onsubmit method instead of the button's onclick method to call the function.
var select_course = function(e) {
e.preventDefault();
// your logic goes here
return false;
}
<form role="form" method="POST" id="subform" name="subform" >
<button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course(event);">placeholder</button>
</form>
Your issue is where the submit event listener is set up.
You need to move this block of code outside the check_conflict() function.
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
.submit(function(e){}) creates a handler for the submit event. In your code, you aren't creating the handler until after the check_conflict function makes it's asynchronous call returns. It's too late. You need the handler already in place when the user submits the form.
<script>
conflict = 0;
$('#subform').submit(function(e){
e.preventDefault();
alert('prevent submit');
});
var select_course = function()
{
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
}
else {
// todo no conflict
}
});
}
</script>
The problem was because of asynchronous behaivor of ajax.
When i click the button, the form submission already starts.
So when i try to check the conflict condition in jquery the form submission has already finished. So i solved the problem by submitting the form just in the if condition in jquery where i get conflict=1 with document.subform.submit().
Before the solution, i was starting the form submission, then i was doing jquery checks.
But now i first make jquery checks, then i do or not do form submission according to jquery search results.
<form role="form" method="POST" id="subform" name="subform">
...
...
#DELETED THIS > <button id="submitbutton" type="submit" class="btn btn-primary" onclick="return select_course();">{% trans "EKLE" %}</button>
#ADDED THIS > EKLE
...
...
<script>
conflict = 0;
var select_course = function()
{
//alert("button clicked");
var selectcourse = document.getElementById('kurskod');
var kurskod = selectcourse.options[selectcourse.selectedIndex].value;
var selectcoursedate = document.getElementById('kursgunu');
var kursgunu = selectcoursedate.options[selectcoursedate.selectedIndex].value;
var selectcoursestart = document.getElementById('kursbasla');
var kursbasla = selectcoursestart.value;
var selectcourseend = document.getElementById('kursbitis');
var kursbitis = selectcourseend.value;
check_conflict(kurskod,kursgunu,kursbasla,kursbitis)
}
var check_conflict = function(kurskod,kursgunu,kursbasla,kursbitis) {
$.get('/check-timetable-timing-conflict', {kurskod: kurskod, kursgunu: kursgunu, kursbasla: kursbasla, kursbitis: kursbitis}, function(data){
objlist = JSON.parse(data);
if (objlist[0] == 1) {
conflict = 1;
alert("Confictval:"+conflict);
var warning = document.getElementById('warningdiv');
warning.innerHTML = "Başka bir kurs ile Saat çakışması var.";
} else {
document.subform.submit(); #ADDED THIS PART
}
});
}
</script>

On click bind to form child button

I have a simple form and I am trying to apply my custom function it like this:
$(document).ready(function(){
$("#async_form").asyncpost(defaultAjaxCallback);
});
$.fn.asyncpost = function(callback)
{
var url = $(this).attr('action');
var btn = $(this).children('input[type=submit]');
var data = $(this).serialize();
$(this).on('click', btn, function(){
event.preventDefault();
$.post(url, data, callback);
});
}
I want to dynamically get the children.btn of form and detect on click on that. This is working but the problem is that where ever on form i click the click is fired. What am I missing here?
The immediate problem is that $.on takes a string in its selector parameter, not a jQuery object. You'll also need to pass event into your click handler, and get the serialized form data in the click handler instead of the ready handler.
$(document).ready(function () {
$("#async_form").asyncpost(null);
});
$.fn.asyncpost = function (callback) {
var url = $(this).attr('action');
$(this).on('click', 'input[type=submit]', event => {
event.preventDefault();
var data = $(this).serialize();
console.log(url, data, callback);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="async_form" action="post.php" method="POST">
<input name="text">
<input name="checkbox" type="checkbox">
<input type="submit">
</form>
Check for current target and target property of event.
e.currentTarget will return element on which you have clicked.
e.target will return element to which the event is attached.
The idea is to check that current target should not be equal to target of event.
Your code will be modified to :-
$.fn.asyncpost = function(callback)
{
var url = $(this).attr('action');
var btn = $(this).children('input[type=submit]');
var data = $(this).serialize();
$(this).on('click', btn, function(e){
if(e.currentTarget != e.target){
event.preventDefault();
$.post(url, data, callback);
}
});
}
You can also do this way :-
$(this).on('click', 'input[type=submit]', function(e){
event.preventDefault();
$.post(url, data, callback);
});
var btn = $("#frm").children('input[type=submit]');
$("#frm").on("click",btn,function(e){
if(e.currentTarget != e.target){
e.preventDefault();
console.log(e.target);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frm">
<input type="submit"/>
</form>

onclick radio button fadeout body and redirect

<div id="language-container">
<form id="language_radio">
<input type="radio" value="//domain.tld/page.php?lang=02" name="language" id="alb">
<label for="alb">Shqip</label>
<input type="radio" value="//domain.tld/page.php?lang=03" name="language" id="eng">
<label for="eng">English</label>
</form>
</div>
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("body").fadeOut(800, newpage);
});
</script>
What I'm trying to accomplish is, when a radio button is selected, I want to fade out the entire body, and then redirect to another page.
However, I can't seem to get it to do anything. It won't fade out or redirect.
How can do I fix it (newb to JS) :)?
You can use:
$("html").fadeOut();
as such:
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
// This variable is useless
// You can remove it if it's not
// being used
newLocation = $(this).val();
$("html").fadeOut(800, function() {
// Redirect to the newLocation here
// similar behavior as clicking on a link
window.location.href = newLocation;
});
});
</script>
try :
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("html").fadeOut(800, function() {
window.location.href = newLocation;
});
});
</script>
you can do this by
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
$("body").fadeOut(1000,function(){
window.location.href = $(this).val();
})
});
jsfiddle

JavaScript Prevent Form Submit

I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.
I have this code:
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var link = $(this).attr("href"); // "get" the intended link in a var
var result = confirm("Are you sure you want to log this fault?");
if (result) {
document.location.href = link; // if result, "set" the document location
}
});
});
The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.
My HTML code is:
<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">
<!-- other elements -->
....
....
....
<button type="submit" id="submit" class="btn btn-default">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
</form>
$(function() {
//this would do the same as button click as both submit the form
$(document).on("submit", "#myform", function (e) {
var result = confirm("Are you sure you want to log this fault?");
//if cancel is cliked
if (!result) {
return false;
}
//if ok is cliked, form will be submitted
});
});
the following like won't work since this reffers to the submit button which does not have an href attribute.
var link = $(this).attr("href"); // is invalid.
try
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var result = confirm("Are you sure you want to log this fault?");
if (result) {
$('#formId').submit(); // where formId is the id of your form
document.location.href = "url to which you want to redirect";
}
else
return false;
});
});
side note: from wherever you got this piece of code, they must be using a hyperlink <a> styled like a button, with a valid href attribute :)

Categories