Django dropdown selection is not working when submit button is pressed - javascript

I have a dropdown selection and 'submit' button in the page. Some fields disappears upon specific dropdown selection. I can hide/show all other fields but except password field. Whenever I hide the password field with a jquery the submit button doesnot work.
following are my code files.
HTML template django
< script >
$(document).ready(function() {
$('#type').change(function(eventObject) {
if ($(this).val() == 'sercomm') {
$('.sample').show();
$('.sample_netip').show();
$('.sample_password').show();
$('.sample_username').hide();
} else {
$('.sample').show();
$('.sample_password').show();
$('.sample_netip').hide();
}
}).change();
});
<
/script>
<form class="form-horizontal" method="post" role="form">{% csrf_token %} {# dropdown#}
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Mode" %}</label>
<div class="col-sm-6">
<select name="type" class="form-control" id="type">
<option value="ex1" selected>{% trans "ex1" %}</option>
<option value="ex2">{% trans "ex2" %}</option>
</select>
</div>
</div>
{# end of dropdown#}
<div class="form-group sample">
<label class="col-sm-3 control-label">{% trans "Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="name" placeholder="{% trans " Name " %}" maxlength="20" id="name" required pattern="[a-zA-Z0-9\.\-_]+">
</div>
</div>
<div class="form-group sample">
<label class="col-sm-3 control-label">{% trans "Management Network IP Address" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="ipaddr" value="192.168.255.129" maxlength="20" required pattern="^(25[0-5]|2[0-4]\d|[0-1]?\d?[1-9]|[0-1]?[1-9][0])(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$">
</div>
</div>
<div class="form-group sample_netip">
<label class="col-sm-3 control-label">{% trans "Radio Network IP Address" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="netipaddr" value="192.168.255.129" maxlength="20" required pattern="^(25[0-5]|2[0-4]\d|[0-1]?\d?[1-9]|[0-1]?[1-9][0])(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$">
</div>
</div>
<div class="form-group sample_username">
<label class="col-sm-3 control-label">{% trans "User Name" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="username" value="" maxlength="48" required pattern="[a-zA-Z0-9\.\-_]+">
</div>
</div>
<div class="form-group sample_password">
<label class="col-sm-3 control-label">{% trans "Password" %}</label>
<div class="col-sm-6">
<input type="password" class="form-control" name="password" value="" maxlength="48" required pattern="[a-zA-Z0-9\.\-_]+">
</div>
</div>
<div class="form-group sample">
<label class="col-sm-3 control-label">{% trans "Description" %}</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="description" value="" maxlength="48" pattern="[a-zA-Z0-9\.\-_ ]+">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
<button type="submit" class="btn btn-primary" name="create" value="1">{% trans "Create" %}</button>
</div>
</form>
forms.py goes here
import re
from django import forms
from django.utils.translation import ugettext_lazy as _
class BaseStationDetailsForm(forms.Form):
type = forms.ChoiceField(required=True, choices=(('nokia', 'nokia'), ('sercomm', 'sercomm')))
name = forms.SlugField(error_messages={'required': _('No base station name has been entered')}, max_length=20)
ipaddr = forms.IPAddressField(error_messages={'required': _('Invalid IP Address')})
netipaddr = forms.IPAddressField(error_messages={'required': _('Invalid IP Address')}) #test
username = forms.CharField(error_messages={'required': _('No user name has been entered')}, max_length=48)
password = forms.CharField(error_messages={'required': _('No password has been entered')}, max_length=48)
description = forms.CharField(required=False, max_length=48)
models.py
from django.db import models
class BaseStation(models.Model):
name = models.CharField(max_length=20)
address = models.IPAddressField()
ipaddress = models.IPAddressField() #tests
username = models.CharField(max_length=48)
password = models.CharField(max_length=48)
description = models.CharField(max_length=48, blank=True, null=True)
status = models.IntegerField(default=0)
def __unicode__(self):
return self.name
views.py (only the create (post) button is gives :
if 'create' in request.POST:
form = BaseStationDetailsForm(request.POST)
if form.is_valid():
data = form.cleaned_data
if basestations and data['name'] in basestation_names:
msg = _("Base Station with this name already exists")
errors.append(msg)
elif ip_addresses and data['ipaddr'] in ip_addresses:
msg = _("IP address " + data['ipaddr'] + " is already assigned to another Base Station")
errors.append(msg)
else:
_type = request.POST.get('type', '')
basestation = BaseStation(name=data['name'],
address=data['ipaddr'],
ipaddress=data['netipaddr'],
username=data['username'],
password=data['password'],
description=data['description'],
status='0')
# test
basestation.save()
return HttpResponseRedirect(request.get_full_path())
else:
for error_key in form.errors:
for error_msg in form.errors[error_key]:
errors.append(error_msg)
### other post button functions code deleted
return render_to_response('basestations.html', locals(), context_instance=RequestContext(request))
Example - I can show /hide username/description, the create button works. Only when password field is hidden, the button does not work.

When you are hiding the password field you also have to remove the required attribute with something like this
$('#password_field').removeAttr('required');​​​​
And then when you show the field add the required again so that the form does not submit without the password.

Your password field have attribute required. Which means that this field is required to submit the form.
To prevent this behavior, during form submission you need to have the following markup.
<div class="col-sm-6">
<input type="password" class="form-control" name="password" value="" maxlength="48" pattern="[a-zA-Z0-9\.\-_]+">
</div>
Mozilla Reference for HTML validations

Related

Javascript, validation of password with bootstrap

i'm trying to learn Javascript and some basic HTML with bootstrap v5.
I created a Sign-in form and now i'm try to do some validation for the required field.
I follow the Bootstrap documentations and i managed to get validation for all my input field except for the password, i want to verify if the password are the same or if they are empty field...but i'm stuck.. not familiar with javascript.
my attempt in javascript:
let forms = document.querySelectorAll(".needs-validations");
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
Array.prototype.slice.call(forms).forEach( function (form){
form.addEventListener("submit",function (ev) {
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.className = 'form-control is-invalid'
pass2.className = 'form-control is-invalid'
}
if (!form.checkValidity()){
ev.preventDefault()
ev.stopPropagation()
}
form.classList.add("was-validated")
})
})
but here the result:
As you can see password is always valid and i don't understand why.
my html:
<body class="body">
<div class="center">
<h4 class="title">Sign Up New User</h4>
<form name="signin-form" method="post" class="needs-validations" novalidate id="forms">
<div class="container">
<div class="row mt-3">
<div class="col">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required>
<div class="invalid-feedback">
Name can't be empty
</div>
</div>
<div class="col">
<label for="surname" class="form-label">Surname</label>
<input type="text" class="form-control" id="surname" placeholder="Surname" required>
<div class="invalid-feedback">
Surname can't be empty
</div>
</div>
</div>
<div class="row mt-3">
<div class="col">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required>
<div class="invalid-feedback">
invalid email
</div>
</div>
<div class="col-4 text-end">
<label for="email" class="form-label">Role</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>Captain</option>
<option>First Officer</option>
</select>
<div class="invalid-feedback">
Please select role
</div>
</div>
</div>
<div class="row mt-3 ">
<div class="col">
<label for="password1" class="form-label ">Password</label>
<input type="password" class="form-control" id="password1" placeholder="Password">
</div>
<div class="col">
<label for="password2" class="form-label ">Confirm Password</label>
<input type="password" class="form-control" id="password2" placeholder="Password">
<div class="invalid-feedback">
Password not match
</div>
</div>
</div>
<div class="row-cols-2 mt-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</div>
<script src="/validation.js"></script>
<script src="/js/bootstrap.bundle.min.js" ></script>
</body>
What I don't understand is, that your password fields seem to be having a valid class in your posted screenshot. But I can't find it anywhere in your code (neither HTML nor JS).
I'd do it like this:
(Note: I didn't test this code, but it should work. If it works and you want to learn from it, I recommend to read through it step by step and apply it to your logic instead of just copy pasta.)
let form = document.querySelector("form.needs-validations");
// or, to be more specific:
// let form = document.querySelector("form[name='signing-form']")
form.addEventListener("submit",function (ev) {
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.classList.add('is-invalid');
pass2.classList.add('is-invalid');
}
if (!form.checkValidity()){
ev.preventDefault();
ev.stopPropagation();
}
form.classList.add("was-validated");
})
Note: the functionality to validate the content of your password-fields will only be triggered once you hit the submit button.

Django does not safe the values of the BooleanFields

I have the following form with few boolean fields:
class RegistrationForm(UserCreationForm):
guardianSource = forms.BooleanField(widget=forms.CheckboxInput(attrs={'id':'guardianSource'}),required=False)
bbcSource = forms.BooleanField(required=False)
independentSource = forms.BooleanField(required=False)
categoryCoronaVirus = forms.BooleanField(required=False)
categoryPolitics = forms.BooleanField(required=False)
categorySport = forms.BooleanField(required=False)
#Telling the registration form what kind of data we are going to be modelling/ what the form needs to look like
class Meta:
model = Account
fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport")
The register template looks as following:
<form class="form-signin" method="POST">{% csrf_token %}
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<label for="username" class="sr-only">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="User name" required autofocus>
<label for="inputPassword1" class="sr-only">Password</label>
<input type="password" name="password1" id="inputPassword1" class="form-control" placeholder="Password" required>
<label for="inputPassword2" class="sr-only">Password</label>
<input type="password" name="password2" id="inputPassword2" class="form-control" placeholder="Confirm Password" required>
<br>
<div class="form-control">
<p><b>Please choose news sources!</b></p>
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="source" id="guardianSource">
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="source" id="bbcSource">
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="source" id="independentSource">
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >Corona Virus</label>
<input type="checkbox" name="category" id="categoryCoronaVirus">
<br>
<label for="categoryPolitics" >Politics</label>
<input type="checkbox" name="category" id="categoryPolitics">
<br>
<label for="categorySport" >Sport</label>
<input type="checkbox" name="category" id="categorySport">
</div>
{% for field in registration_form %}
<p>
{% for error in field.errors %}
<p class="alert alert-danger card-header text-center flashit"> {{ error }}</p>
{% endfor %}
</p>
{% endfor %}
{% if registration_form.non_field_errors %}
<div style="color:red;">
<p>{{registration_form.non_field_errors}}</p>
</div>
{% endif %}
<h6 class="text-muted">
NOTE: You <b>MUST</b> select at least 1 choice for each!!!
</h6>
<div id="error_message"> </div>
<button class="btn btn-lg btn-primary btn-block" type="submit" onclick="valthisform()">Register</button>
</form>
There is a JavaScript function that checks if at least 1 checkbox for category and 1 for source is selected before submitting the form:
function valthisform(){
var guardianSource = document.getElementById("guardianSource").checked;
var bbcSource = document.getElementById("bbcSource").checked;
var independentSource = document.getElementById("independentSource").checked;
var checkedSource = false;
var categoryCoronaVirus = document.getElementById("categoryCoronaVirus").checked;
var categoryPolitics = document.getElementById("categoryPolitics").checked;
var categorySport = document.getElementById("categorySport").checked;
var checkedCategory = false;
if(guardianSource ===true || bbcSource===true || independentSource===true){
checkedSource = true;
}
if(categoryCoronaVirus===true || categoryPolitics===true || categorySport===true){
checkedCategory = true;
}
if(checkedSource ===false && checkedCategory===false){
document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No source and category selected!</div>';
event.preventDefault();
}
else if(checkedSource ===false ){
document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No source selected!</div>';
event.preventDefault();
}
else if(checkedCategory===false){
document.getElementById('error_message').innerHTML = '<div class="alert alert-danger card-header text-center flashit"><strong>Warning!</strong> No category selected!</div>';
event.preventDefault();
}
}
The problem is: when I don't check any checkbox when registering the JavaScript function works as it is supposed to - it prevents saving the data into the database and prints whatever it supposed to. After printing the warning message, I check few boxes and submit the form. Form submits and redirects to home page, however, once I look into the database the checked boolean values are not saved - they are all False.
My django view for register is:
def registration(request):
context = {}
if request.user.is_authenticated: # If user is logged in, redirect to home screen, they cannot register again!
return redirect('home')
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
account = authenticate(username=username, password=raw_password)
login(request, account)
return redirect('home')
else:
context['registration_form'] = form
else: # GET request
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'accounts/register.html', context)
EDIT:
I finally found the bug after going through the commits on git and comparing files to earliest commits.
Basically the code from the register template:
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="source" id="guardianSource">
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="source" id="bbcSource">
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="source" id="independentSource">
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >Corona Virus</label>
<input type="checkbox" name="category" id="categoryCoronaVirus">
<br>
<label for="categoryPolitics" >Politics</label>
<input type="checkbox" name="category" id="categoryPolitics">
<br>
<label for="categorySport" >Sport</label>
<input type="checkbox" name="category" id="categorySport">
</div>
I have renamed for some reason the name attribute of each checkbox.
After changing the values to:
<label for="guardianSource" >The Guardian</label>
<input type="checkbox" name="guardianSource" id="guardianSource">
<br>
<label for="bbcSource" >BBC News</label>
<input type="checkbox" name="bbcSource" id="bbcSource">
<br>
<label for="independentSource" >The Independent</label>
<input type="checkbox" name="independentSource" id="independentSource">
</div>
<br>
<div class="form-control">
<p><b>Please choose news category!</b></p>
<label for="categoryCoronaVirus" >Corona Virus</label>
<input type="checkbox" name="categoryCoronaVirus" id="categoryCoronaVirus">
<br>
<label for="categoryPolitics" >Politics</label>
<input type="checkbox" name="categoryPolitics" id="categoryPolitics">
<br>
<label for="categorySport" >Sport</label>
<input type="checkbox" name="categorySport" id="categorySport">
</div>
It works.
You seem to repeat some of the model fields in your form again. That's not necessary and might cause this error. If you use the following in models.py and forms.py, then calling the save() method should save all fields in your database.
models.py:
class Account(AbstractUser):
guardianSource = models.BooleanField(blank=True, null=True)
bbcSource = models.BooleanField(blank=True, null=True)
independentSource = models.BooleanField(blank=True, null=True)
categoryCoronaVirus = models.BooleanField(blank=True, null=True)
categoryPolitics = models.BooleanField(blank=True, null=True)
categorySport = models.BooleanField(blank=True, null=True)
forms.py:
class RegistrationForm(UserCreationForm):
class Meta:
model = Account
fields = ("username", "password1", "password2", "guardianSource", "bbcSource", "independentSource", "categoryCoronaVirus", "categoryPolitics", "categorySport")
widget = {'guardianSource': forms.CheckboxInput(attrs={'id':'guardianSource'})}

Show add button only when the form is dirty

I have a form with email, password, and password again. I want to hide the add sign by default, and only show it if my form is dirty and password matches password again.
I can’t seem to get it to work.
<div ng-controller="MyCtrl">
Hello, {{name}}!
<form name="addUserForm">
<div class="form-row row">
<div class="col-xs-3 col-sm-3">
<input ng-model="newLogin.email" ng-blur="checkEmailRestriction(newLogin.email)" required type="text" class="form-control input-sm" placeholder="Email">
</div>
<div class="col-xs-3 col-sm-3">
<input ng-model="newLogin.password" required stopccp type="password" class="form-control input-sm" ng-change="checkPwdRestriction(newLogin.password)" placeholder="Password">
</div>
<div class="col-xs-3 col-sm-3">
<input stopccp ng-model="newLogin.passwordAgain" ng-change="checkPwdMatch(newLogin.password,newLogin.passwordAgain)" type="password" class="form-control input-sm" placeholder="Password Again">
</div>
<div class="col-xs-3 col-sm-3">
<a ng-click="storeLogin()" ng-if="newLogin.password === newLogin.passwordAgain && addUserForm.$dirty == false" class="btn btn-xs email-action"> add </a>
</div>
</div>
</form>
<hr>
<p>
object = ? {{newLogin}}
</p>
<p>
$dirty = ? {{addUserForm.$dirty}}
</p>
<p>
$valid = ? {{addUserForm.$valid}}
</p>
</div>
I’ve tried
http://jsfiddle.net/bheng/5pzL8gc3/
I hided your button with this :
ng-show="newLogin.password && newLogin.password == newLogin.passwordAgain && addUserForm.$dirty == true"
And it appears when I provide an email and passwords that match.

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

Checking inputs of form in django before submit

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.

Categories

Resources