Javascript check if BOTH fields contain text - javascript

JS:
function check_form(){
var city = document.getElementById('sCity').value;
var region = document.getElementById('sRegion').value
if ((city != null || city !="") && (region != null || region !="")) {
alert('You can only search with a PostCode OR a City. Please remove either the City or PostCode.');
return false;
}
return true;
}
HTML:
<form action="<?php echo osc_base_url(true); ?>" method="get" class="nocsrf" onSubmit="return check_form()">
<fieldset>
<h3>City</h3>
<div class="row" id="wor1">
<input class="input-text" type="text" id="sCity" name="sCity" value="" />
</div>
</fieldset>
<fieldset>
<h3>Postcode</h3>
<div class="row" id="wor2">
<input class="input-text" type="text" id="sRegion" name="sRegion" value="" />
</div>
</fieldset>
<div class="actions">
<button type="submit">Apply</button>
</div>
</form>
FIDDLE
I need a way to check the two textfields above so that only ONE textfield can be text when the form is submitted. So if user types in a city + postcode, it will alert the user that the form can only take a postcode or a city.
I tried doing this myself but my code doesn't work...

Fix the condition to this:
if ((city != null && city !="") && (region != null && region !="")) {
Note the use of && for each of the two conditions instead of ||. This will make sure that the alert is shown when both fields are filled by the user.

Related

Can I Validate Two Fields Instead of One Field With This JavaScript?

I use the javascript below to validate the Phone Number field on my form by showing the next hidden field whenever the value the user inputs in the phone number field on my form matches with the values in my javascript.
however, if their input does not match with the values in my javascript, the hidden field remains hidden and the user will be unable to submit the form.
The javascript works fine for the phone field but I am trying to validate two different fields to match with the values in my javascript.
For example, I want to make the values users input on the phone field and the email field of my form match with the values in my javascript before the hidden field shows.
Illustration below;
Lets say, the values in my javascript are; if (phone === "12345" && email === "12345#gmail.com")
If the user inputs Phone: 12345 and their email: 12345#gmail.com, the hidden field shows.
If the user inputs Phone:123 and their email: 12345#gmail.com, the hidden field remains hidden.
I have tried different solutions to validate the phone and email field but all my solutions failed and I need some help with this.
Sorry if my solution below is poor but I am not the owner of the original code.
Thanks for your help.
Below is my sample code for the phone field validation. (WORKING FINE!)
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isPhoneInUse(value)) {
$(".validate").show();
} else {
alert ("Phone do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone").val();
if (isPhoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return false;
}
})
function isPhoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<div class="validate"><span style="color: red;"><b>Phone Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>
Below is my solution to validate the phone and email fields. (NOT WORKING!)
$('.validate').hide();
$('body').on('blur', '#phone', '#email', function() {
var value = $(this).val();
if (isDataInUse( $("#phone").val(), $("#email").val() )) {
$(".validate").show();
} else {
alert ("Phone and Email do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#submitForm').on('submit', function(e) {
var value = $("#phone" && "#email".val());
if (isDataInUse( $("#phone").val(), $("#email").val() )) {
// validation failed. cancel the event
console.log("not submitting");
event.preventDefault();
}
})
function isDataInUse(phone, email) {
return (phone === "1234" && email === "1234#gmail.com")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm">
<div class="validate"><span style="color: red;"><b>Phone and Email Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>
After many corrections, here is a working snippet:
$('.validate').hide();
$('#phone, #email').on('change', function() {
let phone = $('#phone').val();
let email = $('#email').val();
if (isDataInUse(phone, email)) {
$(".validate").show();
} else {
alert ("Phone or Email do not match!\nYou cannot submit this form!");
$(".validate").hide();
}
});
$('#theForm').on('submit', function(e) {
let phone = $('#phone').val();
let email = $('#email').val();
if (isDataInUse(phone, email)) {
// validation failed. cancel the event
console.log("not submitting");
e.preventDefault();
return false;
}
})
function isDataInUse(phone, email) {
return (phone === "1234" && email === "1234#gmail.com")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="theForm">
<div class="validate"><span style="color: red;"><b>Phone and Email Matches!</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000" />
<br/><br/>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com" />
<br/><br/>
<div class="validate">
<button href='/' type='submit' id="submitForm">Submit</button>
</div>
</form>

Sweetalert PoP-up message when fields are field is not working

I had a question about Sweetalert a week ago. Then I got an answer which helped me, but unfortunately, it is still not working. I wanted a Sweetalert pop-up message (success) when the user hits the submit button, but only if the fields are filled. I do not know what the problem is. Currently, nothing happens when the user hits the button.
Here is my code:
function Sweetalert1(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var email = document.getElementById("email").value;
if (name != " " && message != " " && email != " "){
Swal.fire(
'Köszönjük!',
'Megkaptuk a leveledet és hamarosan válaszolunk!',
'success',
)}
}
And the part of the HTML:
<form role="form" id="contactForm" action="contact.php" method="post">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Név</label>
<input class="form-control" id="name" name="name" type="text" placeholder="Név" required="required" data-validation-required-message="Kérlek add meg a neved!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Email Cím</label>
<input class="form-control" id="email" type="email" name="email" placeholder="Email" required="required" data-validation-required-message="Kérlek add meg az Email címed!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Üzenet</label>
<textarea class="form-control" id="message" rows="5" placeholder="Üzenet" name="message" required data-validation-required-message="Kérlek írd be az üzeneted!"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div id="success"></div>
<div class="form-group">
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
</div>
</form>
I can't see where the button was fired
On this line,
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
You have at least two options to fire the button
1st
You can change the line to this
<button name="submit" type="submit" class="btn" id="sendMessageButton" onclick="Sweetalert1()">Küldés</button>
2nd
You can add this to your javascript section
$("#sendMessageButton").click(function(){
Sweetalert1();
});
3rd
You can use the form's on-submit event
$("form").submit(function(){
Sweetalert1();
});
When this is done, modify your condition to
if (name !== "" && message !== "" && email !== "")
OR
if (name.trim() && message.trim() && email.trim())
your condition is not right, try doing this:
if (name && message && email)
{
// Code
}
An empty field isn't equal to a space (" "), it is equal to an empty string (""). So, you need to check if the fields equal an empty string, not a field with a space:
if (name != "" && message != "" && email != "") {
// code...
}
However, if you want to treat fields which have no text in them (and just spaces) as invalid as well, you can add the .trim() method to your name, message and email variables. By using trim you can turn inputs such as
" " into "", which will then be treated as an invalid input:
if (name.trim() != "" && message.trim() != "" && email.trim() != "") {
// code...
}
As an empty string is considered falsey (ie "" == false) you don't need to check whether you're input equals an empty string and instead can just check if x.trim() evaluates to true like so:
if (name.trim() && message.trim() && email.trim()) {
// code...
}

How do i check that the textboxes and checkbox has been filled and checked before user can submit the form?

Below shown my JS code and part of the HTML that i wish to create the form. I can't find the reason of why i CAN still submit it when there are fields that are not filled. It should pop up a dialog box according to which fields the user has not fill.
<script>
function validation() {
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
}
if( $('#agree').val() == null || $('#agree').val() == undefined || $('#agree').val() == ""){
alert( 'Please indicate that you have satisfied all the requirements');
}
}
</script>
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" onclick="validation()" >
</div>
</div>
</div>
check box validation was wrong . Iis is(':checked') .And apply the input validation simple with !input value its validate null,empty,undefined ..trim() remove the unwanted empty spaces .
if you have from tag try with onsubmit="return validation()" instead of onclick="validation" submit button. return false its stop the function execution when the input fails
function validation() {
if (!$('#sdate').val().trim()) {
alert('Please fill in start date field');
return false // if you have a form tag
}
if (!$('#edate').val().trim()) {
alert('Please fill in end date field');
return false // if you have a form tag
}
if (!$('#agree').is(':checked')) {
alert('Please indicate that you have satisfied all the requirements');
return false // if you have a form tag
}
else{
console.log('ok')
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form onsubmit="return validation()">
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" class="button" name="submit" value="submit" >
</div>
</div>
</div>
</from>
Try this, It will help you,
$("#btn").click(function()
{
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
return false;
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
return false;
}
if(!document.getElementById('agree').checked) {
alert( 'Please indicate that you have satisfied all the requirements');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-wrapper">
<div class="sub-content">
<div>
<p>Start Date:</p>
<input id="sdate" type="date" name="startdate">
</div>
</div>
<div class="sub-content">
<div>
<p>End Date:</p>
<input id="edate" type="date" name="enddate">
</div>
</div>
</div>
<div class="end-content">
<div class="center-align">
<div class="checklist">
<p>By checking this box I agree that I have satisfied all requirements.</p>
<input id="agree" type="checkbox" name="checkbox" class="tick-att">
</div>
<br>
<div class="align-right">
<input type="submit" id="btn" class="button" name="submit" value="submit" onClientClick="validation()" />
</div>
</div>
</div>
</div>
You need to add return false after every alert. then It will prevent submit event and also it will show the alert message of appropriate field which is first position in the form. If it is not filled immediately the submit event is prevent rest of the alert messages are not shown even the field is empty.
you need to catch the form submit event. The return false statement in the if conditions will stop the event. If everything goes fine, no return false statement will be executed and the form will be submitted.
var validation = function() {
if( $('#sdate').val() == null || $('#sdate').val() == undefined || $('#sdate').val() == "" ){
alert( 'Please fill in start date field');
return false;
}
if( $('#edate').val() == null || $('#edate').val() == undefined || $('#edate').val() == "" ){
alert( 'Please fill in end date field');
return false;
}
if( !$('#agree').is(':checked') ){
alert( 'Please indicate that you have satisfied all the requirements');
return false;
}
}
$("form").submit(function(){
validation();
});

Form validation just for one button

I'm new in web development. I have a form with two buttons, i have a javascript function to validate a form when it is submitted:
function validateForm() {
var freq = document.forms["schedulerForm"]["frequency"].value;
if(freq == null || freq ==""){
alert("Please select a frequency!");
return false;
}
var freqValue = document.forms["schedulerForm"]["frequencyValue"].value;
if (freqValue == null || freqValue == "") {
alert("Please enter a frequency value!");
return false;
}
var email = document.forms["schedulerForm"]["email"].value;
if (email == null || email == "") {
alert("Please add an email!");
return false;
}
}
And the Form: (Adapted for the question purpose)
<form method="post" id="schedulerForm" onsubmit="return validateForm()">
<div class="controls">
<select id="frequency" name="frequency" class="form-control">
<option value="">Select a Frequency</option>
<option value="seconds">Seconds</option>
<option value="minutes">Minutes</option>
<option value="hours">Hours</option>
</select>
</div>
<input type="text" name="frequencyValue" id="frequencyValue">
<input autocomplete="off" class="input" id="email" type="text" placeholder="Enter an email" data-items="8">
<input type="submit" class="btn btn-primary" name="btnStart" value="Start Scheduler" onclick="testScheduler('start')"/>
<input type="submit" class="btn btn-primary" name="btnStop" value="Stop Scheduler" onclick="testScheduler('stop')"/>
</form>
It is working, the function validation works, but i want to restrict this validation just for the first button and not for the other, I thought to take out the second button, but if i do that the form will not be submitted.
Any help will be appreciated!
If you do want both buttons to submit the form, but only 'start' to valid the form before submitting. Remove the onsubmit="return validateForm()" from the form and add it to the onclick of the button.
<input type="submit" class="btn btn-primary" name="btnStart" value="Start Scheduler" onclick="testScheduler('start'); return validateForm();"/>
There are other ways but this would be easiest.

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

Categories

Resources