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.
Related
I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>
I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)
in javascript i can validate a form on submit like below:-
<form action="" method="post" onsubmit="return validate(this)">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
function validate(loginForm){
if(loginForm.uName.value == ''){
alert('Please Enter Username');
loginForm.uName.focus();
}else if(loginForm.passKey.value == ''){
alert('Please Enter Password');
loginForm.passKey.focus();
}else {
return true;
}
}
</script>
I tried with below jQuery Code
<form action="" method="post">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
$('form').submit(function(loginForm){
if(loginForm.uName.val() == ''){
alert('Please enter username');
loginForm.uName.focus();
}else if(loginForm.passKey.val() == ''){
alert('Please enter username');
loginForm.passKey.focus();
}else {
return true;
}
return false;
});
</script>
But not works me... please help me...!
like this?
$('#submit').click(function(){
if( $('#uName').val() == ''){
alert('empty');
}
});
http://jsfiddle.net/TTmYk/
the submit form has a typo in my fiddle u might need to fix that
See the Form Fields jQuery Plugin:
https://github.com/webarthur/jquery-fields
You can use the plugin as follows:
var form = $('form#id_form').fields();
form.name.val('Arthur');
form.age.hide();
form.description.css('height', 200);
Or this way:
var form = $('form#id_form').fieldValues();
form.name('Arthur');
form.age(29);
form.description('Web developer.');
var name = form.name();
The argument in the submit callback function is not the element instead it is the event. So inside the callback this represents the form element so you could just do this.uName.value and you can avoid the use of id as well.
So
$('form').submit(function(e){
if(this.uName.value == ''){
alert('Please enter username');
this.uName.focus();
}else if(this.passKey.value == ''){
alert('Please enter username');
this.passKey.focus();
}else {
return true;
}
return false;
});
Fiddle
Plus val() is jquery method, and in plain javascript you would use value and in this case that should be sufficient enough.
This will help you:
jQuery(function($) {
var $username = $('#uName'),
$password = $('#passKey');
$('form').submit(function() {
if ($username.val() == '') {
alert('Please enter username');
$username.focus();
} else if($password.val() == '') {
alert('Please enter username');
$password.focus();
} else {
return true;
}
return false;
});
});
Some points you need to keep in mind:
If you will work with the DOM you should wrap your code inside a jQuery(function() { ... }); block.
If you want to access a DOM element with jQuery you need to select it before using $(...).
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');
}
});
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
How do i validate these 4 fields so that they are not blank.. without using jquery validate plugin.?
You can cancel the form submission by registering a submit event handler and prevent the default behavior if one of your fields is empty:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]'][value='']", this).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
EDIT: As naveen correctly points out, the code above would still submit the form if the fields only contain whitespace. You can use $.trim() with filter() to fix the problem:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]']", this).filter(function() {
return $.trim(this.value) == "";
}).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
$('input:submit').click(function() {
$('form').submit(function(e) {
$("input:text[name^='member_name']").each(function() {
if (!$.trim($(this).val()).length) {
alert('Name Field should not leave empty');
return false; // or e.preventDefault();
}
});
});
});
var valid = true;
$('input').each(function(){
if($(this).val() == "") {
valid = false;
}
});
// use valid here
var invalidInputs = $('input').filter(function() {
return $(this).val() == "";
});
var valid = invalidInputs.length == 0
Not most advance, but simple & clear method.
$("form").submit(function(event) {
var inputLength = $('input[type="text"]').val().length; // check for value length
if ($('input').val().length > 0) {
// submit if input value is length > 0
alert('Form submitted.');
}
else {
// error if input value is NOT length > 0
alert('Fill the form.');
event.preventDefault();
}
});