i got currently an issue which i cant solve, i have a form which is submitted via Javascript, but i cant prevent it, could you help me. I provided smallest reproducible script.
Thanks in advance.
<form name="f" id="f" action="asd" method="post" enctype="multipart/form-data"></form>
<script>
document.getElementById('f').addEventListener("submit", function(evt) {
evt.preventDefault();
}, true);
window.addEventListener('load', () => {
document.getElementById('f').submit()
}, false )
</script>
I search the documentation of HTMLFormElement.submit and i found that submit event is not fired by using the form.submit. You must use form.requestSubmit See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit and https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit
the issue is the code execution flow. It submit the form before the event listener is added.
To let time for you code to add event listener. I recommand you to execute your submit in the document.onready event.
Here is a quick example: https://jsfiddle.net/7453uvt6/7/
Related
I have a form in that I have User Id availability check. So if Id is already in DB it will show a message "Id is already in use". In that case I have to avoid submitting the form. For that my html is as follow,
<div>
<label><strong>Teacher Id:</strong></label>
<input type="text" name="teacherId" id="teacherId" placeholder="Enter Teacher Id" >
</div><span class="status" id="status"></span>
Here span will have the text about availability,
The value to span comes form jquery post call,
$.post('<%=request.getContextPath()%>/controller/TeacherIdCheckController',
{'teacherId':teacherId},
function(data)
{
$('.status').html(data);
});
}
This works fine, to prevent submitting I wrote javascript function as,
function checkTeacherId(){
alert(" in checkTecherId()");
var status=$("#status").text();
alert(status);
if(status=="Id in use try another")
preventDefault();
else
return true;
}
Everything works fine but this javascript function is not working fine so I cant able to prevent submit in case of Id already exist in DB. So please anyone help me in this.
Just because you need to pass the event in the function's arg:
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
As per your comment you can pass the event to your function in your onclick handler:
onclick="checkTeacherId(event);"
Fiddle
Okay! As #Sanjeev tried commenting on best approach for this work then as you are using jQuery then you can just do this as per best approach like Unobrusive Javascript (removing this inliner scripts just like above posted):
function checkTeacherId(e){ // <---pass the event here
.....
if(status=="Id in use try another")
e.preventDefault(); // and stop it here using dot notation
else
return true;
}
$(function(){
$('#yourformid').on('submit', function(e){
checkTeacherId(e);
});
});
Use this approach if you want to externalize your scripts as declare the function in global scope and put your event handler in doc ready with submit event.
Updated fiddle with unobtrusive way.
Solution as per best practice for form validation:
You have implemented form submit via Submit button and not through js like document.getElementById("myForm").submit();
I don't see any point in using onclick handler on submit button for validation, use the native onsubmit Event Attribute, else you will keep on breaking submit flow.
onsubmit is made for validating form and stopping form submission if validation fails.
This will work sure shot in all browsers and is the correct approach for form validation
Example:
<form action="demo_form.asp" onsubmit="return checkTeacherId()">
function checkTeacherId(){
var status=$("#status").text();
if(status==="Id in use try another"){
return false
}
else{
return true;
}
}
This is my first question posted here, so I apologize in advance if the formatting is not quite as it should be. I am new to JS, and I have now encountered a problem that I have not been able to solve despite extensive use of Google.
I have a dynamically created form, and when that form is submitted I want to add the result to a div and not be redirected. I have tried using both event.preventDefault() and return false; but none of them work. The ajax call works correctly, because the result is visible for a short moment before the redirection. I would appreciate any help with this. This is my JS-code:
$(document).on('submit', '#voteForm', function(event){
event.preventDefault();
alert(event.type);
var choice=$('input[name=choice]:checked').val();
$.ajax( {
type: "POST",
url: "submitVote.php",
data: choice,
success: function(result){
$("#testDiv").html(result);
}
});
});
The HTML-form:
<form id='voteForm' action='javascript:void(0)' method='POST'><!--Changed to action='javascript:void(0)' which made it work-->
<input type='radio' name='choice' value='voteChoice1' checked='checked'>Yes<br />
<input type='radio' name='choice' value='voteChoice2'>No<br />
<input type='submit' id='submitButton' name='submitButton' value='Send'>
</form>
This event binding doesn't look right, try binding the submit event directly to the form instead of the document:
$("#voteForm").on("submit", function(event){
event.preventDefault();
alert("event captured");
...
});
Fiddle: http://jsfiddle.net/4PTdt/2/
event.preventDefault() works against submit handler, according to documentation: http://api.jquery.com/submit/
for "on" event handler you should try event.stopPropagation()
Although the better way would be to do it via jquery-form plugin. See function "ajaxForm" in their online documentation. It does exactly what you want.
At they and of your function just add the following line "return false;". This will stop the form from submitting.
I prefer submitting form values with AJAX by hitting "Return" and all my setups, which I did before, are working, but today it stopped working. Here are the the steps, which I have been following for a quite a long time.
Include jQuery
Setup my form
Preventing it form submitting
$(document).ready(function(){
$(document).on('keyup', myFormSelector, function(event){
if ( event.keyCode === 13 ) {
event.preventDefault();
}
});
});
change the event to keydown and it will work.
try to disable the default behaviour from the submit event and add a SUBMIT-element (display:none).
If a form does have a submit-element, the return key does work like you want it.
Howto disable the submit event:
$('#myForm').submit(function(e) {
e.preventDefault(); // disabling default submit with reload.
// ajax code here
});
if this does not work, u may try this also:
<form id="myForm" onsubmit="return false"> ... </form>
Returning false does stop submitting too.
When using submit elements instead of keyup/keydown, you will be able to add multiple forms on your page with the desired behaviour.
What I want to do is pretty simple.
I've a form, with a submit button
<form accept-charset="UTF-8" action="/some_url" id="some-form" method="post">
...
<button class="btn" id="remove-selected" type="submit">Send</button>`
</form>
I want to change the html of the button with jQuery when the form is submitted but can't achieve that, seems like the form submission occurs before I can change it.
My code right now, dead simple:
$("#some-form").on("submit", function(e) {
$("#remove-selected").html("Sending...");
});
Thanks for advises!
Your stuff seems working for me, just submit the form via JS to have more control about the sequence and error cases.
$("#some-form").on("click", function(e) {
e.preventDefault();
$("#remove-selected").html("Sending...");
$(this).submit();
});
http://jsfiddle.net/GDAhe/1/
$("#remove-selected").click(function(){
$(this).html("Sending...");
});
You code is correct, you may have forgotten to embed it inside a $(document).ready() method.
I have function that submitted two forms at once. And last (the second) post method does not take effect without alert().
Could you please show me my mistake.
function formFunction() {
...
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
//alert('done');
}
UPD
this is how function is calling
<form id="form0" name="form0" onsubmit="formFunction()">
<input id="mainFormValue" type="text">
The reason why it is failing is you are not cancelling the original form submission. That means the page is posting back to the server when you click the button. What you need to do is prevent that origial form submission from completing.
If you are adding the event handler with jQuery, you can use preventDefault() to cancel the form submission.
function formFunction(e) {
e.preventDefault();
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
}
Change the form submission to unobtrusive JavaScript to get the correct event object set by jQuery.
$("#form0").submit(formFunction);
The other solutions is add a return false to the submisison. Just ignore the preventDefault line I suggested above. [bad idea, but will work]
<form id="form0" name="form0" onsubmit="formFunction(); return false">