Form not submiting on chrome but in firefox submitting - javascript

I have a submmit button like Following:
Save & Continue
And My function in js is:
function checkCreditDebit(buttonValues) {
//Some validation here
//Disable Button if once clicked to prevent twice form submission
document.getElementById('saveandcontinue').disabled = 'disabled';
document.getElementById('onlysave').disabled = 'disabled';
}
But when i submit form in firefox it disabled the "save & continue", button and submit form. But in chrome it disable the button but not submit the form. What is the wrong with this please suggest. Thanks in Advance

Instead of just disabling your submit button(forms can also be submitted if you press enter on text-boxes), attach a handler to your form that will leave a 'class name' to your form as a mark that the form was already submitted, if the user submit the form again, the handler should check if the form has already the class name, then prevent duplicate submission via event.preventDefault().
try this:
<form onsubmit="prevent_duplicate(event,this);" action="">
<input type="text" />
<input type="submit" />
</form>
<script>
function prevent_duplicate(event,form)
{
if((" "+form.className+" ").indexOf(" submitted ") > -1)
{
alert("can't submit more than once!!!");
event.preventDefault();
}
else
{
form.classList.add("submitted");
}
}
</script>
Demo here

instead of disabling pervent multiple submit by setting a javascript flag example :
<form method="post" id="ecomFormBean" name="ecomFormBean" onsubmit="return checkSubmit(this);" >
<input type="text" />
<input type="submit" />
</form>
<script>
var formSubmitted = false;
function checkSubmit(f){
if (formSubmitted) {
alert('Please be patient. Your order may take 10 - 15 seconds to process. Thank you!');
return false;
}
else return formSubmitted = true;
}
</script>

Chrome runs javascript very fast. So it might be possible your checkCreditDebit(buttonValues) function which is to disable submit button executes before your php script submits the form.
I suggest you to call setTimeOut function before calling the javascript function so that the form can get submitted.
Give it a try.

Related

How to avoid the user from repeating to fill in the form if there is an error?

Problem: I'm doing a form to be filled by the user. Once the user clicks submit, if there is an error in the form, it will show an alert. However, when the user clicks "ok" the form will reset all the fields that have been filled so the user needs to repeat in fill in the form all over again.
Question: How to fix this so that when the user clicks "ok" the data is still there?
To stop the page from re-loading add return false; after alert statement, it stops the default action from taking place from the form submit.
alert("Please fill in all mandatory fields");
return false;
You should reset form:
document.getElementById("formId").reset();
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
Use <button type="button"> to override default submission behavior.
Use event.preventDefault() in the onSubmit event to prevent form
submission.
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('onSubmit', handleForm);
I have something that does exactly that. It's a complete working code, but I am going to give you the task of figuring out which part does what.
function submitInfo(e){
var fields = document.getElementsByClassName('input-field').length;
for(let x = 0; x < fields; x++){
var value = document.getElementById(x).value;
if(value == ''){
e.preventDefault();
var element = document.getElementById(x);
element.classList.add('no-value');
setTimeout(function(){
element.classList.remove('no-value')
},3000);
break;
}
}
}
.no-value {
border: 2px solid red;
}
<form method="post" action="">
<input type="text" name="email" placeholder="Email" class="input-field" id="0"/><br/>
<input type="password" name="password" placeholder="Password" class="input-field" id="1"/><br/>
<input type="submit" value="Submit" onclick="submitInfo(event)"/>
</form>
I hope this is what you are looking for.

Placeholder only appears for split second [duplicate]

I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>

Prevent Form from Submitting if there are Errors

Before I get into the problem details, I still need to tell you about this form I am creating. I have a Registration form and once the user submits the form by clicking the Submit button, it will NOT go directly to a Successfully Registered page. The user will be seeing a Confirmation page prior to that. In this page, the user will see all the data he inputted for him to review. Below it are the Confirm button and the Return button (if user still likes/needs to edit his details, it will then show the form for him to edit once this button is clicked). But here's the thing, the Registration form page and the Confirmation page are in just the same page. What I did is that when the user submits the form, it will hide some elements including the Submit button and then just show the details he inputted. When the user clicks the Return button on the Confirmation page, it will just then show again the hidden fields so the user can edit his details.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working. I am using bootstrap for my form so when there are errors, the input fields' borders would turn red and would obtain a class has-error. Here's what I did:
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
But again, it is not working. I also googled some jQueries like the .valid() and .validate() functions but I'm not really sure about it and also didn't work for me.
I also did this code where the Submit button should disable when required fields are still empty. And it is perfectly working:
$('#submit').attr('disabled',true);
$('input[id^="account"]').keyup(function() {
if(($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0)) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
I hope you understand my problem. I will make it clearer if this confuses you.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working.
When is it checking for errors? It needs to disable the submit button at the same time it is checking for errors. Your code doesn't work because there's no event telling it WHEN to execute. WHEN do you want submit button to be disabled?
Do you want it triggered when the field is validated or when the form is submitted?
You can't really tie it to the submit button unless you want to click it first to validate the form fields, and then again to submit validated fields. Then you'll need to figure out how to tell it that it's been validated like by a class, maybe? Only accept inputs that hasClass('valid')?
below are the changes
$(".form-group").find("td").each(function() {
if($(this).hasClass('has-error')) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
Try the following
$('#submit').click(function(){
var error = false;
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
error = true;
return false; //break out of .each
}
});
return !error;
});
You can achieve this by maintaining 2 sections.
1. Form section
<form id="form1">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="button" id="confirm" value="Confirm" />
</form>
2. Confirm section
<div id="disp_data" style="display: none;">
<lable>Name: <span id="name_val"></span></lable>
<lable>Email: <span id="email_val"></span></lable>
<input type="button" id="return" value="Return" />
<input type="button" id="submit" value="Submit" />
</div>
You have to submit the form by using js submit method on validating the form in confirm section (When the user clicks on submit button)
$("#submit").click(function(){
var error_cnt = false;
if($("#name").val() == '') {
error_cnt = true;
alert("Enter Name");
}
if($("#email").val() == '') {
error_cnt = true;
alert("Enter Email");
}
if(error_cnt == false) {
$("#form1").submit();
} else {
$("#disp_data").hide();
$("#form1").show();
}
Demo
You have to prevent the form from sumition by return back a boolean false so that it will stop the execution.
$('#submit').click(function(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
if(!ret) return false;
});
If you want to disable the submit button in case of any error you need to monitor the changes of each input fields. so better to give a class name to all those input fields like commonClass
then
function validation_check(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
return ret;
}
$("#submit").prop("disabled",true)
$(".commonClass").change(function(){
if(validation_check()){
$("#submit").prop("disabled",false)
}
else {
$("#submit").prop("disabled",true)
}
});
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error. I've added fiddle you can try.
HTML FORM
<form action="" method="" onsubmit="return dosubmit();">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="submit" value="Submit" />
</form>
JAVASCRIPT
function dosubmit() {
if(false) { //Check for errors, if there are errors return false. This will prevent th form being submitted.
return false;
} else {
return true;
}
}
Let me know if this fixes your issue.

jQuery - doesnt submit data on enter

I am trying to work with a chatroom and some users would like a feature to submit on enter.
I current have this code:
Form html:
<form id="send-message-area" name="send-message-area" method="post" action="">
<textarea id="sendie" name="sendie" maxlength = '255'></textarea>
<input type="submit" name="sendieButton" id="sendieButton" value="Send" />
</form>
jQuery:
$(document).ready(function(){
$("textarea").keyup(function(event){
if(event.keyCode == 13){
//$("form").submit();
$("form").trigger("submit");
}
});
});
However when hitting enter it does indeed submit, however it doesn't send any data with it.
It works just fine when pressing the submit button.
I already tried $("form").submit(); but it does the exact same.
EDIT:
I think the problem lays in my PHP.
if(isset($_POST['sendieButton'])){
$fromID = $brugernavn;
$fromMsg = $_POST['sendie'];
sendMsg($fromID, $fromMsg);
};
However when changing to check for $_POST['send-message-area'] it doesn't work at all.
Your button value will not be submitted until you click on it. So either you trigger its click event
$(document).ready(function(){
$("textarea").keyup(function(event){
if(event.keyCode == 13){
//$("form").submit();
$("#sendieButton").trigger("click");
}
});
});
or check only textarea value isset or not in PHP
if(isset($_POST['sendie'])){
$fromID = $brugernavn;
$fromMsg = $_POST['sendie'];
sendMsg($fromID, $fromMsg);
};
You need to check for name of the textarea not the button
if (isset($_POST["sendie"])) {
$fromMsg = $_POST['sendie'];
}else{
echo "no sendie";
}

Preventing form submission after validation by parsley.js

I have used parsley.js many times and have literally copied the code from my last use of parsley.
However, every time I submit the form the page refreshes. preventDefault seems to work on my other pages and stops the page from refreshing but for some reason when I tried now it won't work. Can anyone figure out why not?
<script>
$(function(){
$("#register_signup").submit(function(e){
e.preventDefault();
var form = $(this);
if ($('#rform').parsley( 'isValid' )){
alert('valid');
}
});
});
</script>
<form id='rform' name='rform' data-parsley-validate>
<input id='reg_password' class='register_input' type='text' autocomplete="off" data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword" placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" onClick="javascript:$('#rform').parsley( 'validate' );" value='Sign Up' />
</form>
You are binding the submit event to a input element. If you check the jquery $.submit() documentation, it states that:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
This is your main problem and this is why alert will never be displayed (in fact, that code is never executed).
I would also change a few things:
$('#rform').parsley( 'validate' ) should be $('#rform').parsley().validate(), assuming you are using Parsley 2.*
$('#rform').parsley( 'isValid' ) should be $('#rform').parsley().isValid().
Use $.on() instead of $.submit().
Remove onClickfrom the register_signup element. Since you are already using javascript, I would do this directly in the javascript code instead of onclick. This is more a personal preference.
So, your code will be something like this:
<form id='rform' name='rform'>
<input id='reg_password' class='register_input' type='text' autocomplete="off"
data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword"
placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" value='Sign Up' />
</form>
<script>
$(document).ready(function() {
$("#rform").on('submit', function(e){
e.preventDefault();
var form = $(this);
form.parsley().validate();
if (form.parsley().isValid()){
alert('valid');
}
});
});
</script>
if you are using parsely 2 you can try this
$(function () {
//parsely event to validate form -> form:valiate
$('#rform').parsley().on('form:validate', function (formInstance) {
//whenValid return promise if success enter then function if failed enter catch
var ok = formInstance.whenValid()
//on success validation
.then(function(){
alert('v');
formInstance.reset();
})
//on failure validation
.catch(function(){
formInstance.destroy();
});
$('.invalid-form-error-message')
.html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
.toggleClass('filled', !ok);
// console.log(formInstance);
if (!ok)
formInstance.validationResult = false;
console.log(formInstance);
});
//parsely event to submit form -> form:submit
$('#rform').parsley().on('form:submit', function (formInstance) {
// if you want to prevent submit in any condition after validation success -> return it false
return false;
});
//default submit still implemented but replaced with event form:submit
$('#rform').submit(function () {
alert('dd');
});
});
for more details parsely documentation check Form with examples and events
When you apply data-parsley-validate to your form, you don't need to apply javascript to form to stop submit until all validation run.
But if you applying javascript return false when parsely() not valid.
And just make sure you have include parsley.js code file.

Categories

Resources