How to prevent Foxycart Action on submit with empty field? - javascript

Hollo All,
I am creating a form that exports data on submit to an ecommerce solution called Foxycart. I would like the form to only proceed onto foxycart when the date field is entered however it currently only displays the alert message then proceeds to the action on the form. Does anyone have advice on how to prevent the action on submit? please see code below:
<script>
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
}
}
</script>
<form name="delivery-date-info" action="https://austin-roman.foxycart.com/cart" method="post" accept-charset="utf-8" onsubmit="return validateForm()">
<div class="add-to-bag">
<label for="datepicker-example3"></label>
<input id="datepicker-example3" type="text" name="Delivery_Date_is">
<input type="submit" id="datepicker-example3" type="text" class="button-add">
</div>
</form>

Assuming you're using FoxyCart's default "sidecart" approach (as of v2.0), you'll need to use FoxyCart's own event system, described here. For your specific example, it might look like this:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
if (validateForm()) {
next();
}
});
};
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
} else {
return true;
}
}
Here's an alternate approach that'd be a bit more flexible, would allow more than one product form per page, and also shows a little more what's going on:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
$element = $(params.element);
if (
$element.attr('name') == 'delivery-date-info'
&& $element.find('[name="Delivery_Date_is"]').length > 0
&& !$element.find('[name="Delivery_Date_is"]').val()
) {
alert('Date must be filled out');
} else {
next();
}
});
};

Related

How to disable preventDefault in an event listener using Vanilla JS

Im still fairly new to JS and would like to be able to remove the event listener that stops the form submitting. I have tried multiple different solutions to do it in JS rather than jquery with no luck. The form currently does not submit, but i cannot get it to reverse should my 'if' conditions be false.
var element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
});
function validateForm() {
var error = "";
if (document.getElementById("name").value == "") {
error += "<p>Name field required</p>"
}
if (document.getElementById("email").value == "") {
error += "<p>Email field required</p>"
}
if (document.getElementById("subject").value == "") {
error += "<p>Subject field required</p>"
}
if (document.getElementById("question").value == "") {
error += "<p>Question field required</p>"
}
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
} else {
var element = document.querySelector('form');
element.removeEventListener('submit', event => {
event.preventDefault();
});
}
}
<div id="errorDiv"></div>
<form id="contact_form" onsubmit="validateForm();">
<button type="submit"></button>
Thanks in advance if anybody can help.
I think you should return true/false from your validateForm() function to prevent/submit the form.
1. You have to return value from the function in the html markup:
<form id="contact_form" onsubmit="return validateForm();">
2. Return true/false from your validateForm() based on validation.
function validateForm() {
var error = "";
................
................
................
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
return false;
} else {
return true;
}
}
Does not required to prevent form submit so remove this code.
var element = document.querySelector('form');
element.addEventListener('submit', event => {
event.preventDefault();
});

Either Can Not submit(); form in jQuery, or can not check if input fields are filled out

I am having trouble submitting the below form.
For background, I'm trying to "submit" a form for a delivery, and I need to know a) their pickup address, b) their dropoff address, and c) their description. I created <p class="error"> fields if those <input>s are empty (as in "Please enter a description").
If I remove the 'return false;' the form submits no matter what, but if I keep the 'return false;' the jQuery works (i.e. - error message appears) but now the form NEVER submits. Thoughts?
Here's my main.js
var main = function() {
$('form').submit(function() {
var pickup = $('#pickup').val();
if(pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if(dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if(description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
return false;
});
};
$(document).ready(main);
var main = function () {
$('form').submit(function () {
var pickup = $('#pickup').val();
if (pickup === "") {
$('.pickup-error').text("Please choose a pickup.");
}
var dropoff = $('#dropoff').val();
if (dropoff === "") {
$('.dropoff-error').text("Please choose a dropoff.");
}
var description = $('#description').val();
if (description === "") {
$('.description-error').text("Please tell us a little about what we're moving.");
}
// did not pass validation
if (pickup != "" || dropoff != "" || description != "") {
return false;
}
// passed validation, submit
return true;
});
};
$(document).ready(main);

Return false does not prevent form submission

I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

return false is not working in javascript validation

function confirmValidation() {
var confirmPass = document.getElementById('newpassword').value;
var newpass = document.getElementById('newpassword2').value;
var passLength = confirmPass.length;
if ((confirmPass == newpass) && (confirmPass != "" && newpass != "") && (passLength > 8)) {
alert("ok");
return true;
} else {
alert("no");
confirmPass.focus();
return false;
}
}
And input:
<input name="register" type="submit" class="alert_button" onclick="return confirmValidation()" value="OK" />
For the return method to work, you need to specify onSubmit attribute/listener to the form tag itself. Like so:
<form method="post" onsubmit="return confirmValidation();">
<!-- OTHER form fields -->
</form>
From w3c documentation:
The onsubmit event occurs when a form is submitted. It only applies to the FORM element.
EDIT
jsfiddle link added.
You must alter your JavaScript a little so that .focus() may fire.
function confirmValidation() {
var confirmPass = document.getElementById('newpassword');
var newpass = document.getElementById('newpassword2');
var passLength = confirmPass.value.length;
if ((confirmPass.value == newpass.value) && (confirmPass.value != "" && newpass.value != "") && (passLength > 8)) {
alert("ok");
return true;
} else {
alert("no");
confirmPass.focus();
return false;
}
}
Move your validation to the form.
document.getElementById('my_form').addEventListener('submit', confirmValidation, false);
You should use onsubmit() event in tag. Now when you submit the form, it will call the function that is written on the onsubmit() event. Only in case of Onsubmit(), it checks the return value if it's true then it proceeds further otherwise not.
<form method="post" onsubmit="return confirmValidation();">
</form>

Categories