I have a form which is cloned using jquery. Because it is cloned, the validation does not work properly.
I have managed to get it give an alert when the field is not filled in, but it still submits the form after the alert message is cleared.
Any ideas?
Code below...
$(document).ready(function(){
$("ul > li > a").click(function() {
$popupCopy = $("." + $(this).attr("href")).html();
$popupAddClass = $(this).attr("href");
$popupWidth = parseFloat($("." + $(this).attr("href")).attr("title")) + 80;
$("<div class='popupContainer'><div class='popupContent " + $popupAddClass + "'>" + $popupCopy + "</div><img src='images/close.png' class='closePopup'></div>").appendTo("body");
$(".popupContainer").fadeIn(500);
return false;
});
$(".giftName").live("focus", function() {
if ( $(this).val()=="Name") {
$(this).val('');
};
});
$(".giftName").live("blur", function() {
if ( $(this).val()=="") {
$(this).val('Name');
};
});
$('.giftSubmit').live('click', function(){
if( ! checkvalid() ) {
alert('Need to fill-out all fields')
}
else {
alert('Thanks')
}
});
});
function checkvalid(){
var valid = true;
$('.giftName').each(function(){
if (this.value == '' || this.value == 'Name' || this.value == null) {
valid = false;
return;
}
})
return valid;
}
body:
<div class="pageContainer">
<div class="bodyPanel">
<ul>
<li>Gift list</li>
</ul>
</div>
</div>
<div class="popupsHidden">
<div class="giftlist">
<form action="sendGift.php" class="giftForm" method="post">
<input name="giftName" class="giftName" type="text" value="Name" />
<input name="" class="giftSubmit" type="submit" value="Send your promised gift..." />
</form>
</div>
</div>
Instead of listening for the click event on the submit button, try listing for the submit event on the form itself:
$('.giftForm').live('submit', function() {
if ( ! checkValid() ) {
alert('not valid !');
return false;
}
});
In your $('.giftSubmit').live('click' ... function, you need to add return false; after showing your validation failure message. This will stop the event from propagating.
Because the click event is not being stopped, the form is being submitted, despite the validation failure.
Related
I am trying to check certain fields in this form and if they aren't correctly filled that it cannot submit. My problem is that when I submit with some fields not filled in it does give the error but it still goes to mail and if I then fill my form in correctly the error doesn't disappear and it doesn't focus like I ask.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var naam = $("#naam").val();
var voornaam = $("#voornaam").val();
var bericht = $("#bericht").val();
if (naam == "" || voornaam == "" || bericht == ""){
$(".error").show();
if(naam == ""){
$("#naam").focus();
}
else if (voornaam == ""){
$("#voornaam").focus();
}
else{
$("#bericht").focus();
}
}
else{
$(".error").hide();
$("form").submit();
}
});
});
</script>
<form action="mailto:#" method="post" enctype="text/plain">
.error {
margin-top: 10px;
color: red;
display: none;
}
If there is an error, the if statement needs to prevent the default behaviour. Pass the event object into the function and call its preventDefault.
$("#submit").click(function(e){
$(".error").show();
e.preventDefault();
You might also try approaching the problem differently; using the <input type="text" required="required"> see https://devdocs.io/html/attributes/required
Problem is that you are not preventing the actual submit of the form.
You can use event.preventDefault();
In the example below, you can see if I have added event.preventDefault(); inside the if statement where it fails. This will do so the form can't be submitted if the "validation" fails.
Demo
$(document).ready(function() {
$("#submit").click(function(event) {
var naam = $("#naam").val();
var voornaam = $("#voornaam").val();
var bericht = $("#bericht").val();
if (naam == "" || voornaam == "" || bericht == "") {
event.preventDefault();
$(".error").show();
if (naam == "") {
$("#naam").focus();
} else if (voornaam == "") {
$("#voornaam").focus();
} else {
$("#bericht").focus();
}
} else {
$(".error").hide();
$("form").submit();
}
});
});
.error {
margin-top: 10px;
color: red;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:nielsvervoort14#gmail.com" method="post" enctype="text/plain">
<input id="naam" />
<input id="voornaam" />
<input id="bericht" />
<button id="submit">submit</button>
<div class="error">error</div>
</form>
You can use the event preventDefault method. just like that.
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
// or return false;
});
});
You need to call e.preventDefault() only when there is an error that should prevent the form from submitting.
Also, the better way to check for empty fields is to check for the presence of only whitespace, not just comparing against an empty string:
$(document).ready(function(){
$("#submit").click(function(e){
const re = /^\s*$/
var naam = $("#naam").val();
var voornaam = $("#voornaam").val();
var bericht = $("#bericht").val();
if (re.test(naam) || re.test(voornaam) || re.test(bericht)){
e.preventDefault(); // Stop form from submitting
$(".error").show();
if(re.test(naam)){
$("#naam").focus();
}
else if (re.test(voornaam)){
$("#voornaam").focus();
}
else{
$("#bericht").focus();
}
}
else{
$(".error").hide();
$("form").submit();
}
});
});
This will indicate an error when the user not just leaves a field blank, but also fills in only spaces.
I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:
I have a form with all types of form elemnts and I have a code that should run through every single one of the elemnts and check their value after the submit button is clicked. Unfortunatelly, this code doesn't work completely. What I mean is that if I don't enter any value in the input, it will print the message, but if I enter some text in it, we go to the else statement, without checking the other.
Could somebody tell me why?
if($('form.registration-form :input').val() == '')
{
// Print Error Message
}
else
{
// Do something else
}
You can use filter method for this:
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
// all IS filled in
} else {
// all is NOT filled in
}
$('#submit').click(function(){
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
alert('All Filled');
} else {
alert('1 or more not filled')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" class="registration-form">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="submit" id="submit" value="Check">
</form>
I have this form that has 3 inputs and when a user leaves a field blank a dialogue box pops up to alert the user a field is blank. The code I have below only works for 2 specific input. When i try adding another input to the code it doesnt work. It only works for 2 inputs. How can I make it work for all three?
<script type="text/javascript">
function val(){
var missingFields = false;
var strFields = "";
var mileage=document.getElementById("mile").value;
var location=document.getElementById("loc").value;
if(mileage=='' || isNaN(mileage))
{
missingFields = true;
strFields += " Your Google Map's mileage\n";
}
if(location=='' )
{
missingFields = true;
strFields += " Your business name\n";
}
if( missingFields ) {
alert( "I'm sorry, but you must provide the following field(s) before continuing:\n" + strFields );
return false;
}
return true;
}
</script>
Showing 3 alerts may be disturbing, use something like this:
$(document).on('submit', 'form', function () {
var empty = $(this).find('input[type=text]').filter(function() {
return $.trim(this.value) === "";
});
if(empty.length) {
alert('Please fill in all the fields');
return false;
}
});
Inspired by this post.
Or you can do validation for each field this way using HTML data attributes:
<form data-alert="You must provide:" action="" method="post">
<input type="text" id="one" data-alert="Your Google Map's mileage" />
<input type="text" id="two" data-alert="Your business name" />
<input type="submit" value="Submit" />
</form>
... combined with jQuery:
$('form').on('submit', function () {
var thisForm = $(this);
var thisAlert = thisForm.data('alert');
var canSubmit = true;
thisForm.find('input[type=text]').each(function(i) {
var thisInput = $(this);
if ( !$.trim(thisInput.val()) ) {
thisAlert += '\n' + thisInput.data('alert');
canSubmit = false;
};
});
if( !canSubmit ) {
alert( thisAlert );
return false;
}
});
Take a look at this script in action.
Of course, you can select/check only input elements that have attribute data-alert (which means they are required). Example with mixed input elements.
You can add the required tag in the input fields. No jQuery needed.
<input required type="text" name="name"/>
Try this
var fields = ["a", "b", "c"]; // "a" is your "mile"
var empties= [];
for(var i=0; i<fields.length; i++)
{
if(!$('#'+fields[i]).val().trim())
empties.push(fields[i]);
}
if(empties.length)
{
alert('you must enter the following fields '+empties.join(', '));
return false;
}
else
return true;
instead of this
var name = $('#mile').val();
if (!name.trim()) {
alert('you must enter in your mile');
return false;
}
So i want to alert the user if they submit the form with an empty text field
HTML:
<form id="orderform">
<input type="text" name="initials" id="initials" maxlength="3">
<p class="center">
<input type="image" src="#" id="submitbutton" name="submit" value="Place Order">
</p>
</form>
Javascript:
$('#orderform').submit(function() {
if($('#initials').length == 0){
alert('Please fill out your initials.');
}
});
Just make sure you return false in there somewhere-
$('#orderform').submit(function() {
if($('#initials').val() == ''){
alert('Please fill out your initials.');
return false;
}
});
$('#initials').length will check if the element exists. Try this:
$('#orderform').submit(function() {
if($('#initials').val().length == 0){
alert('Please fill out your initials.');
}
});
as lewsid pointed out, you should also return false if you want to cancel the submit
$('#orderform').submit(function(e) {
e.preventDefault();
if(!$.trim((this + ' input').val()).length){
alert('Please fill all the fields');
return false;
}
return true;
});
but is better if you do this with pure JS not jQuery
function funnjsTrim(input) {
return input
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '')
.replace(/([\s]+)/g, '-');
}
validate_form = function(form, mssg){
mssg = form_errors[mssg] || 'Error: empty field';
var form_to = form.name,
elems = document.forms[form_to].getElementsByTagName("input");
for(var i = 0; i < elems.length + 1; i++) {
if(elems[i].type != 'submit') {
var string = funnjsTrim(elems[i].value);
if(!string.length) {
alert(mssg);
error = 'error';
return false
}
}
}
if(typeof error == "undefined"){
alert('Valid');
return true;
}
}
so in your html
<form onsubmit="return validate_form(this)">
in this line: if(elems[i].type != 'submit') add || elems[i].class != 'your input class' to add exceptions
I'd use e.preventDefault() instead of return false. Return false also prevents events from bubbling and can have unintended consequences if you don't understand this. Also nest that preventDefault within your if, no reason to stop submission if things are good.
$('#orderform').submit(function(e) {
if(!$.trim($(this).find('input[type="text"]').val()).length){
e.preventDefault();
alert('Please fill all the fields');
}
});