Prevent Form from Submitting if there are Errors - javascript

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.

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.

Form not submiting on chrome but in firefox submitting

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.

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";
}

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources