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>
Related
am having problem making this to work on submit
it works well when using
document.getElementById("gets").addEventListener("click", b_button);
but not workng when i use
document.getElementById("gets").addEventListener("submit", b_button);
is there away to make it work on submit than using click
<form method="post">
<button type="submit" id="gets">Submit</button>
<p id="error"></p>
</form>
<script>
function b_button() {
document.getElementById("gets").disabled = true;
var time_meter = 10;
var runTimer = setInterval(function() {
if (time_meter <= 0) {
clearInterval(runTimer);
document.getElementById("error").innerHTML = "";
} else {
document.getElementById("error").innerHTML = 'counting ' + time_meter;
}
time_meter -= 1;
}, 1000);
setTimeout(function() {
document.getElementById("gets").disabled = false;
}, 10000);
}
document.getElementById("gets").addEventListener("submit", b_button);
</script>
you have to listen to form submit not to button submit
<form id="form" method="post">
document.getElementById("form").addEventListener("submit", function(e){ .... }
do not forget on e.preventDefault(); inside of your code to prevent unwanted submiting
Pressing the enter button on the keyboard, the HTML button (id="botonCorregir") should be pressed automatically, but does nothing.
HTML:
<form id="theFormID" class="text-center">
<input autofocus id="respuestaUsuario" type="text">
<button id="botonCorregir" onclick="corregir()">Responder</button>
</form>
JAVASCRIPT:
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
</script>
<script>
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
For example if y try that, and push enter, doesn´t show alert "hello!". Why?
<script>
if (event.keyCode == 13) {
alert("hello!");
}
</script>
The usual way to do it in html/js is this one:
HTML
<form id="my-form">
<!-- creating a form, we use the on-submit event -->
<input type="text" autofocus id="respuestaUsuario" />
<button type="submit">Responder</button>
</form>
JS
// submit event runs when the user click the submit button or press enter on the input-text
document.getElementById('my-form').addEventListner('submit', evt => {
evt.preventDefault();
corregir();
});
Let me know if it's not clear enough and I'll try to explain it better.
the keyup event listener is for when you release the enter key
plus you can call the corregir function directly instead of triggering a click on the button
try :
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
});
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
also, a submit would be more addapted to this situation since the submit triggers itself on enter if an element of it's form is selected
Try to call the function direktly without clicking the button.
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
<script type="text/javascript>
function submitMe() {
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
}
</script>
<input type="hidden" name="jsfields" id="jsfields" value="">
I'm searching the way to get checked Ids of Jstree in form submit. So this is what I get. However, how I can call this function in my program?
Use a click/submit event
$(form).submit(submitMe);
or
$('[type="submit"]').click(submitMe);
Don't forget to prevent the default event and then trigger it after the code:
function submitMe(e) {
e.preventDefault();
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
window.location = $(this).closest('form').submit();
}
I have this Javascript and HTML code for my button:
function lockoutSubmit(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function(){
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
<button style="margin-right:-160px;" type="submit" name="gen" onclick="lockoutSubmit(this)" class="btn btn-danger btn-block">Generate account!</button>
The code works fine for disabling the button for 3 seconds but the button is no longer posting to "gen".
Change the innerHTML instead of the value and bind the parameters to the settimeout instead of relying on the context.
Also button value might not be what you think it is:
http://www.w3schools.com/tags/att_button_value.asp
<html>
<head>
<script>
function _Unlock(){
var tB = document.getElementById('gen');
tB.removeAttribute('disabled');
tB.innerHTML = 'Generate account!';
localStorage.setItem('Lock', 0);
}
function Unlock(){
var tS = localStorage.getItem('Lock');
if (tS != '1') _Unlock()
else{
setTimeout(function(e, v){
_Unlock()
}, 3000)
}
}
function setToLock(){
localStorage.setItem('Lock', 1);
}
</script>
</head>
<body onload = 'Unlock()'>
<!-- Do you have a form and is it setup correctly? -->
<form action = '' method = 'post' id = 'myForm' onsubmit = 'setToLock()'>
<button id = 'gen' type = 'submit' name = 'gen' disabled = 'disabled'>...processing...</button>
<form>
</body>
</html>
Submitting a file with ajaxSubmit() works fine when the form is hard-coded. But the data received by the server is empty when the form is created dynamically.
This version works
HTML
<form id='file_upload_form' method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" id='myfile' name="myfile" />
<br/>
<input type="submit" />
</form>
<div id='status'> </div>
JavaScript
jQuery(document).ready(function() {
jQuery("#file_upload_form").on("submit", function(e) {
e.preventDefault();
jQuery(this).ajaxSubmit({
target: '#status'
});
});
});
Debuggin in .on("submit"... , jQuery(this).formSerialize() yields "myfile=%5Bobject+File%5D"
But this version using a dynamically created form sends empty data
HTML
<div id='parent_elem_div'> </div>
<div id='status'> </div>
JavaScript
jQuery(document).ready(function() {
var parent_elem = jQuery('#parent_elem_div');
var new_form_elem = build_form();
parent_elem.append(new_form_elem);
});
jQuery(document).ready(function() {
jQuery("#file_upload_form").on("submit", function(e) {
e.preventDefault();
jQuery(this).ajaxSubmit({
target: '#status'
});
});
});
But here, debuggin in .on("submit"... , jQuery(this).formSerialize() yields "".
This function builds the form...
//
function build_form (){
var new_inner_div_elem = document.createElement('div');
new_inner_div_elem.id = 'parent_elem_div';
var upload_form = document.createElement('form');
upload_form.id = 'file_upload_form';
upload_form.action = '/upload';
upload_form.method = 'POST';
upload_form.enctype="multipart/form-data";
var file_input = document.createElement('input');
file_input.type = 'file';
file_input.id = 'file_upload_input';
var file_upload_submit = document.createElement('input');
file_upload_submit.type = 'submit';
upload_form.appendChild(file_input);
upload_form.appendChild(file_upload_submit);
new_inner_div_elem.appendChild(upload_form);
return new_inner_div_elem;
}
Aha! Here it go, in your code:
var file_input = document.createElement('input');
file_input.type = 'file';
file_input.id = 'file_upload_input';
This is missing:
file_input.attr('name', 'myfile');
This is the only part that your HTML form has, and dynamical doesn't, so I guess that's the trick
If an HTML doesn't have a name it won't be passed to the
querystring or the POST data - there will be no way to retrieve it
from PHP
This is from here - stackoverflow