Prevent form from submitting when certain fields are empty - javascript

I would appreciate your help on this one. I tried to use code from other questions, but unfortunately it doesn't work.
I am trying to prevent a form from submitting and show an alert ("Select dates so continue")if two specific fields are empty. In this case "checkin" & "checkout"
This is the code for the first input field:
<input type="text" id="checkin" readonly="true" name="checkin" class="form-control search-input" placeholder="Check-in date" data-provide="datepicker-inline" data-date-orientation="bottom" data-date-autoclose="true" data-date-start-date="now" data-date-format="<?php echo $javascriptLocal ?>" data-date-language="<?php echo $language ?>"required>
<div class="input-group-addon search-icon-right" onclick="$('#checkin')[0].focus()" onfocus="$('#checkin')[0].focus()">
Code for the second field:
<input type="text" readonly="true" id="checkout" name="checkout" class="form-control search-input" placeholder="Check-out date" data-provide="datepicker-inline" data-date-orientation="bottom" data-date-autoclose="true" data-date-start-date="now" data-date-format="<?php echo $javascriptLocal ?>" data-date-language="<?php echo $language ?>"/>
<div class="input-group-addon search-icon-right" onclick="$('#checkout')[0].focus()" onfocus="$('#checkout')[0].focus()">
I tried to achieve it with this javascript:
<script type="text/javascript">
function empty() {
var x;
x = document.getElementById("checkout").value;
if (x == "") {
alert("Select dates to continue");
return false;
};
}
</script>
However, this does not work. Could your please help me?
EDIT:
This is the Javascript that seems to interfere with my code: Any suggestions?
<script>$(document).ready(function(){$(".gotop").on("click",function(){$("html, body").animate({scrollTop:$("body").offset().top},1000)});$("#child").on("change",function(){var a=$(this).val();if(a<=0){$(".child-age-1-container").fadeOut("slow");$(".child-age-2-container").fadeOut("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-1").val(0);$("#child-age-2").val(0);$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==1){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeOut("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-2").val(0);$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==2){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==3){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeIn("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-4").val(0)}else{if(a>=4){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeIn("slow");$(".child-age-4-container").fadeIn("slow")}}}}}});$("#checkin").datepicker().on("changeDate",function(){var a=$("#checkin").datepicker("getDate");a.setDate(a.getDate()+2);$("#checkout").datepicker("setDate",a);$("#checkout")[0].focus()});$(".btn-hotel-search").on("click",function(a){a.preventDefault();var j=$("#search-form");var g=$("#child-age-1").val();var f=$("#child-age-2").val();var e=$("#child-age-3").val();var d=$("#child-age-4").val();var b;var c=$("#child").val();var h="";for(b=1;b<=c;b++){h+=$("#child-age-"+b).val()+","}h=h.substr(0,h.length-1);j.append($('<input type="hidden" name="childages">').val(h));j.get(0).submit()})});</script>

Use HTML5 required attribute on the input elements, the form wont be submitted if the fields are empty. to learn more about html5 validation please visit
http://www.the-art-of-web.com/html/html5-form-validation/

You can try like this:
$('form').on("submit",function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
alert('Stopped');
})
Or by button
$('#submitButton').on("click",function(e) {
e.preventDefault();
alert('Stopped');
})

First thing you can do is mark your checkout field as required, jsut like checkin this would help.
Second you can trace your values with temporary alerts while debugging, this helped me a lot when looking for javascript issues.
Third you can try to use a strict comparaison operator and be a bit more specific with the function return values as such
<script type="text/javascript">
function empty() {
var x = document.getElementById("checkin").value;
var y = document.getElementById("checkout").value;
if (x === "" || y === "") {
alert("Select dates to continue");
return false;
};
return true;
}
</script>

You can try something like this in javascript
if(!x){
alert('Stopped');
}
In Javascript every variable can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.
Hope it help

Just change it to
if (!x) {
alert("Select dates so continue");
return false;
}
This will check if variable is null, empty, or undefined

use the "required" attribute for the specific input tag
just give input type="submit" below that
<input type="number"
name="stock"
required
onChange={(e)=>{this.setState({ quantity: e.target.value , number: val.qty})}}/>
<input type="submit" />
WORKS PERFECT!!!

Related

Check value from a string after a special character if it's not empty

im working in little projet, and i have a little issue
So first im working in a form with differents inputs
the first input called by ID is #name
I try to write a code to check if my user fill the input correctly with this tructure
fisrtname_lastname
what i try to do on my sence, is to check first if the user type ( _ ) in the input, and check if he continue to add more infos after the special character.
and the others steps is when he fill in the right way the submit button is actif
$('#submit').removeAttr('disabled');
if its not its gona be inactif
$('#submit').attr('disabled', 'disabled');
** input code**
<input type="text" class="form-control text" name="p_Nom" id="name" maxlength="24" placeholder="firstname_Prenom" />
** Jquery part **
$('#name').keyup(function() {
$('#submit').attr('disabled');
let val = $(this).val();
if( (val.includes('_')) && (val.substr(val.indexOf('_') + 1) == null) ){
$('#submit').removeAttr('disabled');
} else{
$('#submit').attr('disabled', 'disabled');
}
});
You might consider using a regex instead: use the pattern [A-Za-z]+_[A-Za-z]+ for the input. No jQuery necessary:
<form>
<input pattern="[A-Za-z]+_[A-Za-z]+">
<button>Submit</button>
</form>
Or, to permit other non-alphabetical characters, use a negative character set instead:
<form>
<input pattern="[^_]+_[^_]+">
<button>Submit</button>
</form>
If you also need to run Javascript when invalid, add an invalid event listener:
$('input').on('invalid', () => {
console.log('invalid');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input pattern="[^_]+_[^_]+">
<button>Submit</button>
</form>

Javascript code depending on phpvariable

Im running a form in a webshop that looks like this:
<form>
<input type="number" name="quantity" value="" required = "required" />
<input type="radio" name="homeDelivery" value="" required = "required" checked="true" />
<input type="radio" name="homeDelivery" value="" required = "required" />
<input type="submit" value="buy" name="submitBuy" class="buy formConfirm" />
</form>
After the submit button is pressed I run a simple error check in php from the info I get from $_POST. I have an array called $errors, if my error check finds any errors it adds them to my array, else not, and if the array stays empty til the end, my form will submit the data, else not.
I do however want to have a JS confirmbox after pressing submit, that will only popup if there are no errors in the actual form. So to my actual question:
Is it possible to check in javascript code if my $errors variable is empty? Something that works like this:
if(empty($errors)) {
//run code
}
If it is possible Id like my javascript code to look something like this(I think you get the idea);
$('.buyConfirm').on('click', function(){
if (errors == NULL) {
return confirm('Are you sure?');
}
else {
return false;
}
});
Any help is appreciated,
Cheers!
You need to output your PHP var as a JS array, best using json_encode, and then consume that in your condition
<script>
var errors = <?php echo json_encode($errors); ?>;
if (errors.length < 1) {
if (confirm("Are you sure?")) {
// User has no errors and has confirmed
} else {
// User has no errors but did not confirm
}
} else {
// User has errors
}
</script>

Validate form's textarea - jQuery

I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.
I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.
This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:
<form id="colleagues" action="email-sent.php" method="POST">
<input type="hidden" name="user" value="user" />
<textarea id="emails" name="emails" value="emails" placeholder="Example: john#mail.com, thiffany#mail.com, scott#mail.com..."></textarea>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
Here is what I tried in Jquery with no success:
//handle error
$(function() {
$("#error_message").hide();
var error_emails = false;
$("#emails").focusout(function() {
check_email();
});
function check_email() {
if(your_string.indexOf('#') != -1) {
$("#error_message").hide();
} else {
$("#error_message").html("Invalid email form.Example:john#mail.com, thiffany#mail.com, scott#mail.com...");
$("#error_message").show();
error_emails = true;
}
}
$("#colleagues").submit(function() {
error_message = false;
check_email();
if(error_message == false) {
return true;
} else {
return false;
}
});
I hope the question was clear enough, if you need more info please let me know.
Many thanks in advance for all your help and advises.
var array = str.split(/,\s*/);
array.every(function(){
if(!validateEmail(curr)){
// email is not valid!
return false;
}
})
// Code from the famous Email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Few errors as I noted down:
The code snippet posted here has missing braces }); at the end.
Also, what is your_string variable in the function check_email.
Also, error_message is assigned false always so the submit method will return true always.
Fixing this issues should help you.
I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():
<form id="colleagues" action="" method="POST">
<input type="hidden" name="user" value="user" />
<input name="emails[]" id="starter" placeholder="Email address" />
<div id="addEmail">+</div>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function() {
$("#addEmail").click(function() {
$("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
});
});
</script>
Hi please use below js code,
$('#emails').focusout(function(e) {
var email_list = $('#emails').val();
var email_list_array = new Array();
email_list_array = email_list.split(",");
var invalid_email_list=' ';
$.each(email_list_array, function( index, value ) {
if(!validEmail(value))
{
invalid_email_list=invalid_email_list+' '+value+',';
}
});
console.log(invalid_email_list+' is not correct format.');
alert(invalid_email_list+' is not correct format.');
})
function validEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.
thank you
Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...

Javascript Validation Not Working When Submitting

I've been developing my first website, and I'm having issues with a javascript validation script. My code:
<html>
<head>
<title>Territory</title>
</head>
<body>
<script type="text/javascript"> //Main Javascript function giving me issues
function validate(form)
{
fail = validateTerrNum(document.checkOut.numberOut.value);
fail += validateFirstName(document.checkOut.fName.value);
fail += validateLastName(document.checkOut.lName.value);
if (fail == "")
return true;
else
{
alert(fail);
return false;
}
}
</script>
<script type="text/javascript>
function validateTerrNumber(field)
{
if (field == "") return "No territory number was entered. \n";
else if (field.length > 3)
return "Territory numbers must be less than four characters. \n";
else if (/[^0-9]/.test(field))
return "Only 0-9 allowed in territory number. \n";
return "";
}
//Note: Does not sanitize string
function validateFirstName(field)
{
if (field == "") return "No first name was entered. \n";
return "";
}
//Again, note that this function does not sanitize string
function validateLastName(field)
{
if (field == "") return "Not last name was entered. \n";
return "";
}
</script>
<table border="0" cellpadding="2" cellspacing="5">
<th colspan="2" align="center">Check Out</th>
<form name="checkOut" method="post" onSubmit="validate(this)">
<tr><td>Territory Number</td><td><input type="text" name="numberOut" tabindex="1" maxlength="3" size="3" /></td>
</tr><tr><td>First Name of Holder</td><td><input type="text" name="fName" tabindex="2" maxlength="15"/></td>
</tr><tr><td>Last Name of Holder</td><td><input type="text" name="lName" tabindex="3" maxlength="15" /></td>
</tr><tr><td><input type ="checkbox" name="specialC" tabindex="4" value="Yes"/> Special Campaign</td>
</tr><tr><td></td><td><input type="submit" value="Check Out" /></td>
</form>
</table>
</body>
</html>
It is obviously poorly formatted - result of copy and paste. To be more specific, this issue is with the javascript validation. When I hit "Check Out," the validation does not prevent it when I put in bad values. The script is quite simple, but for some reason I can't figure out what is going on with it (I'm fairly new to javascript).
I know the issue is not my browser as I have many javascripts running throughout it. The only thing I can think of is that the form does not have a method. It will be another validation, but written in php - the javascript is really just a prevalidation for the client.
Any help would be appreciated.
-Mlagma
To stop the submit going ahead after validation fails you need:
onSubmit="return validate(this)"
instead of your current code:
onSubmit="validate(this)"
Your validate() function already returns true or false, but those values were not being returned from the event handler itself. If you think of the code between the quotes of onSubmit="" as the body of a function this makes sense.
And, asTeemu pointed out, your validate() function tries to invoke a function called validateTerrNum when actually you've declared that function as validateTerrNumber.
With these problems corrected you can see it working here: http://jsfiddle.net/nnnnnn/Wvcy3/
You have this line in validate():
fail = validateTerrNum(document.checkOut.numberOut.value);
And there is this function:
function validateTerrNumber(field){...
Also document.checkOut is undefined rather than form element (browser dependent???), it's better to use document.getElementById('numberOut').value instead, (same for fName and lName). Ofcourse you'll need to add these ids in the HTML.

If input2 empty copy value from input1?

This is my first message here so I hope that newbies also get help :)
My problem is following:
let's start with code first....
javascript:
$(document).ready(function(){
if ($("input#datum2").val() == "")
{
$().click(function(){
$("input#datum2").val($("input#datum1").val());
});
}
});
html:
<form >
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
What I want this script to do is that first checks if input field datum2 is empty. If yes, than copy value from input#datum1. This action is suppose to happen each time user clicks (anywhere on page?)...
When user types something in datum1 and clicks somewhere than this value is copied to datum2. The problem is when user edits datum1 or datum2, than this value is again copied to datum2. Obviously this condition
if ($("input#datum2").val() == "")
works only once.
I'm new to javascript and jquery so I would appreciate for any help.
Thanks in advance!
Cheers,
Ile
Sounds like you'll need to bind to a different event. Blur occurs when an input loses focus, which sounds like what you're after.
$(function() {
var $datum2 = $('#datum2');
$('#datum1').blur(function() {
if(!$datum2.val())
$datum2.val($(this).val());
});
});
Couple of things:
1) $(function() { ... is a nice shortcut to $(document).ready
2) In JavaScript, an empty string evals to false, so its a nice shortcut.
I see the way round are the order of the click event and "if ($("#datum2",..."
HTML:
<form id="myform">
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
Javascript:
$(document).ready(function(){
$().click(function(){
if ($("#datum2", $("#myform")).val() == "") {
$("#datum2", $("#myform").val($("#datum1", $("#myform")).val());
}
});
});
$(document).ready(function(){
var $datum2 = $('#datum2');
$('#datum2').hover(function() {
if(!$datum2.val())
$datum2.val($('#datum1').val());
});
});

Categories

Resources