I'm using bootstrap 4 styling for my application. Application has two text boxes and one submit button. When you click the "Save" button it will call a web API and get some details asynchronously(it will not redirect the page).
Validation applied for the first text box only.
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Test Page</title>
</head>
<body>
<form class="container needs-validation" novalidate>
<div class="form-group row mt-5">
<label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="tel" class="form-control" placeholder="Please enter your name" required />
<div class="invalid-feedback">
Please enter the name.
</div>
</div>
</div>
<div class="form-group row mt-5">
<label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
<div class="col-sm-10">
<input type="tel" class="form-control" />
</div>
</div>
<div class="form-group row">
<input type="submit" class="btn btn-primary" style="width: 100px;" value="Save" />
</div>
</form>
</body>
</html>
My problem:
When I click the "Save" button without entering any values to the text boxes, green color style(validation true style) is applying to the "Address" textbox. I don't wont that to happen.
I only need red color style(validation failed style) to be applied if the validation is failed. If the values are entered(validation is true), I don't need any styling to be applied to the text boxes.
Also when I enter some value to the "Name" text box and click the "Save" button, I don't want green color styling for that text box.
Screenshot:
I, for one, do not like overriding the CSS style so you could also choose to just specify which fields to validate instead of the entire form.
Add a class to your .form-group element (e.g. .validate-me)
<form class="container needs-validation" novalidate>
<div class="form-group row mt-5 validate-me">
<label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="Please enter your name" required />
<div class="invalid-feedback">
Please enter the name.
</div>
</div>
</div>
<div class="form-group row mt-5">
<label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
<div class="col-sm-10">
<input type="tel" class="form-control" formnovalidate="formnovalidate" id="address" />
</div>
</div>
<div class="form-group row">
<input type="submit" class="btn btn-primary" style="width: 100px;" value="Save"/>
</div>
</form>
Now change your JavaScript slightly, retrieve all the form-groups with the validate-me class and instead of calling form.classList.add('was-validated') loop through all the captured form-groups and add was-validated to them instead.
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Get all form-groups in need of validation
var validateGroup = document.getElementsByClassName('validate-me');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
//Added validation class to all form-groups in need of validation
for (var i = 0; i < validateGroup.length; i++) {
validateGroup[i].classList.add('was-validated');
}
}, false);
});
}, false);
You might want to look at this answer.
Specifically, instead of adding .was-validated to the entire form, only add .is-invalid to the form elements which have the :invalid pseudo-class.
This code should work in your case:
for (var i = 0; i < validateGroup.length; i++) {
var invalidGroup = validateGroup[i].querySelectorAll(":invalid");
for (var j = 0; j < invalidGroup.length; j++) {
invalidGroup[j].classList.add('is-invalid');
}
}
You can override css of the is-valid validation. When you right click on the green check box and choose inspect you can see which class is causing the green light
So you should specify to not inherit those from bootstrap. The code should be like this :
<!DOCTYPE html>
<html>
<head>
<style>
.form-control.is-valid:focus, .was-validated :valid.form-control{ border-color:inherit !important;
background-image: inherit !important;
box-shadow:inherit !important;}
</style>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Test Page</title>
<script type="text/javascript">
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
</head>
<body>
<form class="container needs-validation" novalidate id="myFrom" >
<div class="form-group row mt-5">
<label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="tel" class="form-control" placeholder="Please enter your name" required />
<div class="invalid-feedback">
Please enter the name.
</div>
</div>
</div>
<div class="form-group row mt-5">
<label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
<div class="col-sm-10">
<input type="tel" class="form-control" />
</div>
</div>
<div class="form-group row">
<input type="submit" class="btn btn-primary" style="width: 100px;" value="Save"/>
</div>
</form>
</body>
</html>
What I added is the style tag and css options below the head tag.
Override the $form-validation-states scss variable. This is documented in Bootstrap 5 but the same technique applies to version 4.
https://v5.getbootstrap.com/docs/5.0/forms/validation/#customizing
$form-validation-states: (
"valid": ( <-- delete this
"color": $form-feedback-valid-color,
"icon": $form-feedback-icon-valid
),
"invalid": (
"color": $form-feedback-invalid-color,
"icon": $form-feedback-icon-invalid
)
);
(function () {
'use strict';
window.addEventListener('load', function () {
const forms = document.getElementsByClassName('needs-validation');
Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
const invalidGroup = form.querySelectorAll(":invalid");
for (let j = 0; j < invalidGroup.length; j++) {
invalidGroup[j].classList.add('is-invalid');
}
}, false);
});
}, false);
})();
The post from #Ilker Kadir Ozturk worked for me by just using style, except that my valid field border inherited from a prior color (Black) which I did not want to use. I am using Bootstrap 4 and ASP.NET MVC in a razor page. Here is his code adjusted with my color (#DDDDDD). I included my comments also above the styles :
#* This is to prevent the green color style on Bootstrap validation to be applied to all textboxes when the info is valid.
Only the red color style(validation failed style) should be applied if the validation failed.
If the values are ok, no styling should be applied to the text boxes.
Also when the "submit" button is clicked, there is no need for the green color styling to show up either.
*#
<style>
.form-control.is-valid:focus, .was-validated :valid.form-control {
border-color: #DDDDDD !important;
background-image: inherit !important;
box-shadow: inherit !important;
}
</style>
A partial Solution to Remove Styling In Case Validation Was Successful
If form.checkValidity() evaluates true, remove was-validated class from the form.
An example in React Bootstrap:
Having <Form noValidate validated={this.state.validated} onSubmit={this.onSubmit}>
onSubmit = (e) => this.setState({ validated: !e.currentTarget.checkValidity()});
Here is my solution to a similar problem using jQuery:
In your submit method, insert the following lines after calling checkValidity():
$("#myForm").find(":valid").parent().removeClass("was-validated"); // Optional: Removes all green borders that have been fixed since last submit attempt
$("#myForm").removeClass("needs-validation");
$("#myForm").find(":invalid").parent().addClass("was-validated");
This solution only adds red borders to invalid inputs. Once they have been corrected, though, they will be displayed with a green border, but personally, I still prefer this over a forest of green fields if only one input is invalid ...
I would like to summarize this using an example. This one includes:
Validations for some fields you need adding class value
"validate-me"
Remove the green validation style
Refresh the invalid validation
This example will contain three html inputs:
the html code for this example is:
<form class="needs-validation " novalidate>
<div class="validate-me">
<label for="firstNameId">First name</label>
<input type="text" class="form-control" id="firstNameId" required>
<div class="invalid-feedback">
Please provide a first name.
</div>
</div>
<div class="">
<label for="miId">MI</label>
<input type="text" class="form-control" id="miId" required>
<div class="invalid-feedback">
Please provide a MI name.
</div>
</div>
<div class="validate-me">
<label for="lastNameId">Last name</label>
<input type="text" class="form-control" id="lastNameId" required>
<div class="invalid-feedback">
Please provide a last name.
</div>
</div>
...
</form>
For validation, include the following js function:
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Get all form-groups in need of validation
var validateGroup = document.getElementsByClassName('validate-me');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
//Added validation class to diva in need of validation
for (var i = 0; i < validateGroup.length; i++) {
var invalidGroup = validateGroup[i].querySelectorAll(":invalid");
for (var j = 0; j < invalidGroup.length; j++) {
invalidGroup[j].classList.add('is-invalid');
invalidGroup[j].addEventListener("input", e => e.target.classList.remove("is-invalid"), { once: true });
}
}
}, false);
});
}, false);
Therefore, the validation will be applied just to fields that have class value: "validate-me", green validation will be removed and the red invalid message will be auto refreshed.
Example with no green validation:
Related
i'm using bootstrap's form validation to validate a form. i wan to add an extra field called discount code. this field should accept only specified codes. when the field is empty it should light green, when the code is right it should light green and when the code is wrong it should light red. how can i do that using the bootstrap form validation?
thats how my form almost looks like
<form class="needs-validation" novalidate>
<div class="form-group">
<div class="col-md-12">
<strong>Enter your name </strong>
<input type="text" name="name" id="name" class="form-control" value="" required minlength="3" />
<div class="invalid-feedback">
Name should be at least 3 characters
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
<script>
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="/style.css">
</head>
<body>
<div class="container mt-4">
<h1 class="text-left" style="margin-bottom: 50px">Daily Fridge & Freezer Monitoring Record</h1>
<form action="/auth/21-TEMP-01b" method="post" id="form">
<div class="form-group">
<label>Select Fridge Or Freezer</label>
<select class="form-control" id="fridgeFreezer" name="fridge">
<option value="Fridge-1">Fridge 1</option>
<option value="Fridge-2">Fridge 2</option>
</select>
</div>
<div class="form-group fridges Fridge-1">
<h4>Fridge 1</h4>
<label>Temperature °C</label>
<input class="form-control" type="number" id="temperature-1" name="temperature-1">
<label>Comments</label>
<textarea class="form-control" rows="3" id="comments-1" name="comments-1"></textarea>
</div>
<div class="form-group fridges Fridge-2">
<h4>Fridge 2</h4>
<label>Temperature °C</label>
<input class="form-control" type="number" id="temperature-2" name="temperature-2">
<label>Comments</label>
<textarea class="form-control" rows="3" id="comments-2" name="comments-2"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$(this).find("option:selected").each(function(){
if($(this).attr("value")=="Fridge-1"){
$(".fridges").not(".Fridge-1").hide();
$(".Fridge-1").show();
}
else if($(this).attr("value")=="Fridge-2"){
$(".fridges").not(".Fridge-2").hide();
$(".Fridge-2").show();
}
else{
$(".fridges").hide();
}
});
})
.change();
var temp1 = document.getElementById('temperature-1');
var form = document.getElementById('form');
form.addEventListener('submit', function(e) {
if(temp1.value === '' || temp1.value == null) {
e.preventDefault()
document.querySelector('#fridgeFreezer [value="Fridge-1"]').selected = true;
alert("temp1 not fully filled")
}
})
});
</script>
</body>
</html>
Idea
I am trying to create form validation.
Running the above code details
You will see when you change the option in the drop down menu - different div element loads up. This is done through the jQuery code in the script.
Option 1
Option 2
Next, Javascript
I will be using Javascript to validate the form.
I only have started out validating the first div element of fridge 1. If value is empty I have an alert saying which input has not been filled.
In this scenario I have cleared out all data from Fridge 1 to run the if statement for the error.
Notice this line of code:
document.querySelector('#fridgeFreezer [value="Fridge-1"]').selected = true;
This re-selects the option to the one has the error.
But when I run it - this happens.
Div element of fridge-2 is still showing? How come is the jQuery not executing ?
You have to trigger a change event if you want the change event listener to execute.
form.addEventListener('submit', function(e) {
if(temp1.value === '' || temp1.value == null) {
e.preventDefault()
$('#fridgeFreezer').val("Fridge-1"); // can be simplified like this
$('#fridgeFreezer').trigger("change"); // important line
alert("temp1 not fully filled")
}
})
I know this is a simple fix but through multiple google searches, I can't seem to find the answer to my question. I'm using a validation form from bootstrap 4, and I'm just trying to add functionality to my button by simply linking it to a different page. I tried using the anchor tag,
i.e. Submit
which will work, but the obviously validation is bypassed.
so currently I have this button within a form:
<button class="btn btn-primary" type="submit" >Submit form</button>
</form>
with this java script:
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
What needs to be added to the js to make the button functional?? Thank you for any assistance!!
Here's a simplified version, the code is heavily commented.
// wait for page to load then run the code inside
window.onload = () => {
// Select the form we want to validate
let form = document.querySelector('form');
// listen for submit event
form.onsubmit = (event) => {
// prevent the form from posting so the page won't refresh
event.preventDefault();
// debugging log statememnet (not needed)
console.log('Form submitted')
// checking for form validation
if (form.checkValidity() === false) {
// if we're inside this if statement, the form is invalid
// we add the boostrap class to handle styling
form.classList.add('was-validated');
// debugging log statememnet (not needed)
console.log('Form not valid')
} else {
// if we're inside this if statement, the form is valid and ready for further actions
// debugging log statememnet (not needed)
console.log('Form valid')
// redirect to the target page
location.href = "www.example.com"
}
}
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-3">
<label for="validationCustomUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
If you're a beginner i suggest you stay away from libraries and just play with vanilla js/css build everything from scratch if you get stuck your research on every single line of code, Then and only then you can start messing with libraries and such.
i created a simple form to submit a text.
This text inpout is required.
But if I click on the submit button the form is sent even though the required text is empty.
I used this bootstrap example template
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
// 'use strict'
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation')
// Loop over them and prevent submission
Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
}, false)
}())
$("#suche").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div id="karte1" class="col-md-7 order-md-1">
<form class="needs-validation" id="suche" novalidate>
<div class="mb-3">
<div class="input-group">
<input type="text" class="form-control" id="username2" required>
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary">
submit
</button>
</div>
<div class="invalid-feedback" style="width: 100%;">
Valid text is required.
</div>
</div>
</div>
</form>
</div>
<!-- Karte1 -->
</div>
<!-- row -->
</div>
<!-- container -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
Thanks for your help!
Could you maybe use the html required attribute instead?
This should be a comment but I do not have enough reputation.
I have to submit the form only if all the input fields which has the required="required" attribute.
My form:
<form method="post" action="/actions.php/" data-js-validate="true" data-js-highlight-state-msg="true" data-js-show-valid-msg="true">
<input type="text" name="amount[]" required="required" placeholder="Amount" class="inputChangeVal" data-js-input-type="number" />
<input type="text" name="grade[]" required="required" placeholder="Amount" class="inputChangeVal" data-js-input-type="number" />
<button class="btn" type="submit" name="confirm" >Pay Now</button>
</form>
I wanted to submit the form after showing a message box.
As you see my form action is another php file.
so I prevent the default behavior and then send the form if the continue button is clicked.
I use bootsrap for that.
Bootstrap model :
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Proccess Payment</h4>
</div>
<div class="modal-body">
<p>
"Your about to make a online payment. Click 'Edit' to review the data before proceeding or click 'Continue' to confirm the details for payment."
</p>
<button class="btn btn-default" data-dismiss="modal">Edit</button>
<button class="btn btn-primary" id="continuebtn">Continue</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
and the jQuery for that:
<script>
jQuery( document ).ready(function() {
/* for boot strap model */
jQuery('#payBtn').on('click',function(e){
e.preventDefault();
jQuery('#myModal').modal('toggle');
});
jQuery('#continuebtn').on('click',function(){
jQuery('form').submit();
});
});
</script>
but this one sends the from if I click the button Continue button.
No matter the input fields are filled or not..
What I want is the form should be submitted only if the fileds required="required" are filled..
how can I do this?
first of all add a id attribute on your submit button with the name of 'payBtn'.
after that
replace the following jquery with your current js
<script>
jQuery( document ).ready(function() {
jQuery('#payBtn').on('click',function(e){
e.preventDefault();
var empty = false;
jQuery('input:text').each(function(){
if(jQuery(this).val()==''){
console.log('error');
empty = false;
} else empty = true;
});
if(empty)
jQuery('#myModal').modal('toggle');
else
console.log('your error message');
});
jQuery('#continuebtn').on('click',function(){
jQuery('form').submit();
});
});
$('form').on('submit', function(event){
event.preventDefault();
event.stopPropagination();
var check = true;
$('*[requiered]').each(function(){
// run other filter functions here
if($(this).val().trim().length < 1){
check = false;
}
´ });
if(!check){
alert('something is missing');
} else {
// all is fine
$(this).submit();
}
})
something like this?
You can add some conditions in your jQuery function :
jQuery('#continuebtn').on('click',function(){
if($("#myInput").val() != "")
{
jQuery('form').submit();
}
});
This way, you can do specific actions for each input.
But there is another method which consist to check all inputs containing "required" attribute at once
var missingFieldCounter = 0; // we count the number of field missing
jQuery('#continuebtn').on('click',function(){
$(':input[required]').each(function() // for each input that contains "required" attribute
{
if($(this).val() == "") // if the required input is not filled
{
missingFieldCounter+=1;
$(this).after("<b>You have to fill this field</b>"); // we print a message after the input
}
});
if(missingFieldCounter == 0) // if the counter has never been incremented (every field is filled)
{
jQuery('form').submit();
}
});
See the fiddle Here
here is a working sample
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test-Projekt</title>
<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=10">
<link href="favicon.ico" rel="Shortcut icon">
</head>
<body>
<form action="" method="GET">
<div>
<label>required input</label>
</div>
<div>
<input type="text" name="myInput" required>
</div>
<div>
<button id="btn_submit" type="submit">Submit Form</button>
</div>
</form>
</body>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous">
</script>
<script type="application/javascript">
$(document).ready(function(){
$('#btn_submit').on('click', function(event){
event.preventDefault();
event.stopPropagation();
var formElement = $(this).parents('form');
formElement.find('input:required').each(function(){
var minLength = 1;
var value = $(this).val();
var checked = true;
if(value.trim().length < minLength) {
console.log('length is not ok');
checked = false;
}
if(!checked){
console.log($(this).attr('name') + ' is not correctly filled!');
} else {
console.log('all is ok');
formElement.submit();
}
});
});
});
</script>
</html>
by the way. if you use html 5 the and you don't do anything, every input filed with the required property will be checked by modern browsers automaticly. that's the reason because i don't use it if don't have to filter fields for special chars.
If $('#formid').submit() doesn't show the missing fields like when we click on submit button, then what about creating a hidden submit button and simulating a click?
If you put something like the following inside your form:
<input id="send" type="submit" style="display: none"/>
Now the JavaScript part:
$(document).ready(function(){
$('#continuebtn').on('click', function(event){
$('#send').trigger('click');
})
});
You'll see that when you click on your #continuebtn you'll get the missing fields.
The browser already knows where are the missing fields. It's much more productive to reuse it instead of writing jquery calls and reinvent the wheel.
I believe that this is not the best solution but it works with very little modification of our code base.
You can easily make a field required by including required within the input type.
My example:
<div class="contact-form-value">
<input required type="text" name="PhoneNumber" id="phonenumber">
</div>