Checking inputs of form in django before submit - javascript

I am using Django and try to submit a form.
I have a "call-us" form and there is 3 fields.
I want to make this, If one of the fields is empty, and the user clicked on Submit button, don't send the info to View and warm the user that they must complete the required fields.
here is my form:
<form role="form" action="{% url "landingpages:callusthanks" %}" method="post" style="max-width: 500px;margin: 0 auto;margin-top: 30px;">
{% csrf_token %}
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i></div>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-at"></i></div>
<input type="text" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-envelope-o"></i></div>
<textarea name="message" class="form-control" id="message" placeholder="Message"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-6">
<button type="submit" class="form-control">Send</button>
</div>
</div>
</form>

As one option you can use jQuery validation and set the required fields like so:
$(document).ready(function(){
$("#your_form_id").validate({
rules :{
your_field : {
required : true
}
.....
},
messages :{
your_field : {
required : 'your_field is required'
}
.....
}
});
});
Edit: Just saw you said not to send to view. So, ignore this but I'll leave it for future reference on the off chance that it's useful.
Preferably, you could turn this into a form import it from forms.py and then send it to your view. You could then just set which fields are required.

Related

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

jquery each method not working as expected

I am currently working on a website and this particular section requires the user to enter their details in a form. What I am trying to achieve is the following;
If the user hits the submit button and any fields are empty, I want a span element, which is initially set to CSS display none, to show up for each respective input field which has not been filled.
However, nothing seems to be happening when I click on the button. When I go to the console, it does not display any error message.
Can someone please assist? Many thanks.
HTML:
<!-- START OF 'YOUR DETAILS' FORM-->
<section>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Email is required!</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Name is required!</span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="tel" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Contact Number is required!</span>
</div>
<div class="form-group">
<label for="postcode">Post Code:</label>
<input type="text" placeholder="Post Code" id="postcode" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Post Code is required!</span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="tel" placeholder="DD/MM/YYYY" id="dob" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
DOB is required!</span>
</div>
</form>
<div class="form-group">
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
</div>
</section>
<!-- END OF YOUR DETAILS FORM -->
JS / JQUERY:
$("#submit").click(function(){
var $formValues = $(".your-details");
var $warning = $(".warnings");
$($formValues).each(function(index){
if ($(this).val("")){
$($warning[index]).css("display","block");
}
})
})
When your running this code $($formValues).each(function(index){if ($(this).val("")){ console.log(this) and see in which context your function is running, the issue is that every time you write a function declaration it creates a new this context and thus the previous this is lost.
Your selectors are kind of redundant, keep the form from submission and show the warnings when any are empty seems to be your intent.
$("#submit").click(function(e) {
$(".your-details").each(function(index) {
if ($(this).val() =="") {
e.preventDefault();// no submit if not filled out
$(this).next('.warning').css("display", "block");// next sibling show
}
});
});
Thought about this for a bit and believe you might handle the form submit instead
$("form").on('submit', function(e) {
$(this).find('.warning').css("display", "none");// hide in case they fix input values
$(this).find(".your-details").each(function(index) {
if ($(this).val() =="") {
$(this).next('.warning').css("display", "block");// next sibling show
}
});
});
Alternately you might use a filter.
$("form").on('submit', function(e) {
$(this).find('.warning').css("display", "none");// hide in case they fix input values
var emptyInputs = $(this).find(".your-details")
.filter(function() {
return ($(this).val() =="");
});
if(!!emptyInputs) {
e.preventDefault();
emptyInputs.next('.warning').css("display", "block");
}
});
Except typo, there was one problem more, you are actually setting value, instead of checking it: if ($(this).val("")) If you change it, and fix typo, something like this should work. Simplified, your code could look like this:
$("#submit").click(function(){
var $formValues = $(".your-details");
$($formValues).each(function(index){
if ($(this).val()==''){
$(".warning").eq(index).css("display","block");
}
else {
$(".warning").eq(index).css("display","none");
}
})
})
Demo:
$("#submit").click(function(){
var $formValues = $(".your-details");
$($formValues).each(function(index){
if ($(this).val()==''){
$(".warning").eq(index).css("display","block");
}
else {
$(".warning").eq(index).css("display","none");
}
})
})
.warning {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- START OF 'YOUR DETAILS' FORM-->
<section>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Email is required!</span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Name is required!</span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="tel" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Contact Number is required!</span>
</div>
<div class="form-group">
<label for="postcode">Post Code:</label>
<input type="text" placeholder="Post Code" id="postcode" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
Post Code is required!</span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="tel" placeholder="DD/MM/YYYY" id="dob" class="form-control your-details">
<span class="warning"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i>
DOB is required!</span>
</div>
</form>
<div class="form-group">
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
</div>
</section>
<!-- END OF YOUR DETAILS FORM -->
P.S. You can keep your: $($warning[index]) vars, but you should hide warnings, anyway (else block), if field is not empty.

contact us web page using Ajax and php

I would like to create contact us web page without refreshing the page when click send button. My code bellow, but there are some problems:
1- The page is refreshed after submitting the form.
2- The value of the Contact form inputs appear in the URL after submitting the form. check this image
3- The confirmation message appears for 0.25 seconds then disappear or does not appear.
4- The email is not received to my email address when I use Firefox browser.
Please help me to solve those problems.
HTML
<div class="col-sm-8 col-sm-offset-2" id="mail-status">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-8 col-xs-12 col-sm-offset-2">
<div class="well">
<form class="form-horizontal">
<fieldset>
<legend class="legend-title">I'd <span class="heart"><i class="fa fa-heart"></i></span> to contact you!</legend>
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="name" placeholder="Name" required="required">
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" required="required">
</div>
</div>
<div class="form-group">
<label for="inputSubject" class="col-sm-2 control-label">Subject</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputSubject" name="subject" placeholder="Subject" required="required">
</div>
</div>
<div class="form-group">
<label for="textAreaMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-9">
<textarea class="form-control" rows="5" id="textAreaMessage" name="message" placeholder="Message" required="required" minlength=5 ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-8">
<button type="submit" class="btn btn-primary right-button" id="send" onClick="sendContact()">Send</button>
</div>
</div>
</fieldset>
</form>
Javascript
function sendContact() {
jQuery.ajax({
url: "send_email.php",
data:'inputName='+$("#inputName").val()+'&inputEmail='+$("#inputEmail").val()+'&inputSubject='+$("#inputSubject").val()+'&textAreaMessage='+$(textAreaMessage).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
php
<?php
$toEmail = "*****#***.com";
$mailHeaders = "From: " . $_POST["inputName"] . "<". $_POST["inputEmail"] .">\r\n";
if(mail($toEmail, $_POST["inputSubject"], $_POST["textAreaMessage"], $mailHeaders)) {
print "<div class='alert alert-success'> <button type='button' class='close' data-dismiss='alert'>×</button> Thank you for your email! I will be in touch.</div>";
} else {
print "<div class='alert alert-danger'> <button type='button' class='close' data-dismiss='alert'>×</button> We are sorry, but there is a problem. Please Make sure all fields are filled!</div>";
}
?>`
Get rid of the inline onclick() event in your HTML, and let your JavaScript handle the click:
$('#send').click(function(e){
e.preventDefault();
sendContact();
});
preventDefault() stops the click event from acting normally, so your form data is submitted without reloading the page.

AngularJS - How can set the true value for ng-disabled directive, when the page is loaded first time?

I have this form with validation in AngularJS:
<form ng-app="myApp" ng-controller="validateCtrl as validate" name="myForm" action="sendEmail" novalidate>
<div class="form-group">
<input type="email" name="email" class="form-control" ng-model="validate.email" placeholder="Email" required>
<span style="color:yellow" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</div>
<div class="form-group">
<input type="text" name="subject" class="form-control" ng-model="validate.subject" placeholder="Subject" required>
<span style="color:yellow" ng-show="myForm.subject.$dirty && myForm.subject.$invalid">
<span ng-show="myForm.subject.$error.required">Subject is required.</span>
</span>
</div>
<div class="form-group">
<textarea type="text" name="message" class="form-control" ng-model="validate.message" placeholder="Message..." required></textarea>
<span style="color:yellow" ng-show="myForm.message.$dirty && myForm.message.$invalid">
<span ng-show="myForm.message.$error.required">Message is required.</span>
</span>
</div>
<button type="submit" class="btn btn-lg btn-success"
ng-disabled="myForm.email.$dirty && myForm.email.$invalid ||
myForm.subject.$dirty && myForm.subject.$invalid ||
myForm.message.$dirty && myForm.message.$invalid"></button>
</form>
The button is disabled until the email, subject and message aren't correct. Ok, it's fine. But that is true, only if I have already interacted with the form.
In fact, when the page is loaded the first time and I haven't interacted with the form yet, the button is enabled. So, if I click it, I could send an empy email! I would that when the page is loaded the button is disabled and when I fill the fields become enabled.
How can I do that?
Thanks.
You first condition can be ng-disabled=" myForm.email.$invalid . Remove "myForm.email.$dirty
Try like this
<form name="postForm" method="POST" novalidate>
<div class="col-md-8">
<div class="col-md-12">
<div class="col-md-12"><legend>Submit New Post</legend></div>
</div>
<div class="col-md-12 form-group">
<div class="col-md-12" ng-class="{ 'has-error' : postForm.title.$invalid && !postForm.title.$pristine }">
<input type="text" placeholder="Write Title" class="form-control" name="title" ng-model="post.title" required>
<p ng-show="postForm.title.$invalid && !postForm.title.$pristine" class="text-danger">* Write Post Title</p>
</div>
</div>
<div class="col-md-12 form-group">
<div class="col-md-12" ng-class="{ 'has-error' : postForm.url.$invalid && !postForm.url.$pristine }">
<input type="url" placeholder="Write URL" class="form-control" name="url" ng-model="post.url" >
<p ng-show="postForm.url.$invalid && !postForm.url.$pristine" class="text-danger">* Write URL in http:// or https:// Format</p>
</div>
</div>
<div class="col-md-12">
<div class="col-md-12" >
<p class="text-danger">{{msg}}</p>
</div>
</div>
<div class="col-md-12 form-group">
<div class="col-md-12"><button type="submit" class="btn btn-info" ng-disabled="postForm.$invalid" ng-click="submitForm(....)">Submit</button>
<img src="img/loading.gif" ng-show="loading" /></div>
</div>
</div>
</form>
On your submit button, modify the ng-disabled to this:
ng-disabled="myForm.$invalid || myForm.$pristine">
In this case, you don't have to validate all your inputs separetely. Just test if your form is invalid OR if the user never interacted with it yet.
A form in AngularJS has two different states: pristine and dirty. The pristine indicates that your form was never touched. And dirty is the opposite. When the user set any value to one of your inputs, the angular change the state of your form from pristine to dirty.
I guess this post is a good reference to read about forms in angular

Error in submitting form using ajax

For some reason, the form is not getting submitted. I have used ajax form to save the form details in my database.
Here is the site link:
http://www.famproperties.com/mudon/Abu-Dhabi/villas.html
Here is the script code.
<script>
$(document).ready(function() {
$("#submit-form-button").click(function() { submitForm(); });
});
function submitForm() {
if ( $("#NAME").val() == '' ||
$("#EMAIL").val() == '' ||
$("#MOBILE").val() == '' ||
$("#NOTE").val() == '' )
{ alert ("All field are required");}
else {
$.ajax({
type: "POST",
url: "http://famproperties.com/real_estate/property/contact/lead/",
data: {
NAME: $("#NAME").val(),
EMAIL: $("#EMAIL").val(),
MOBILE: $("#MOBILE").val(),
NOTE: $("#NOTE").val(),
SOURCE: 'MSB.COM'
},
success: function() {
alert("Thanks, Our specialist will contact you soon.");
},
dataType: 'html'
});
$("#NAME").val('');
$("#EMAIL").val('');
$("#MOBILE").val('');
$("#NOTE").val('');
}};
</script>
Here is the form code.
<!--NEW FORM -->
<div class="form-horizontal" role="form" accept-charset="UTF-8" action="http://famproperties.com/real_estate/property/contact/lead/" autocomplete="on" id="pro-form" method="post">
<div class="form-group">
<label for="NAME" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="NAME" required="" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="EMAIL" class="col-sm-2 control-label ">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="EMAIL" required="" placeholder="me#example.com">
</div>
</div>
<div class="form-group">
<label for="MOBILE" class="col-sm-2 control-label">Mobile</label>
<div class="col-sm-10">
<input type="phone" class="form-control inputs" id="MOBILE" required="" placeholder="Mobile">
</div>
</div>
<div class="form-group">
<label for="NOTE" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="NOTE" required="" placeholder="Note">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<a href="#" onclick="return false" class="btn btn-default btn-lg button" id="submit-form-button" style="background-color: #ffc600;
color: #2a292a;
width: 100%;"> Submit <span class="fa fa-chevron-right fa-1x"></span><span class="fa fa-chevron-right fa-1x"></span> </a>
</div>
</div>
</div>
<!--NEW FORM-->
Seeing the page on http://www.famproperties.com/mudon/Abu-Dhabi/villas.html you are not even loading jquery check the console and youll see this error:
Uncaught ReferenceError: $ is not defined
Thats why ajax is not working
Edit: Sorry, checking your code again i saw you are loading jQuery but you are trying to use jQuery before loading it. So, try moving the jquery script tag to the header or move your js below the jQuery script tag.

Categories

Resources