I have a registration from. I am trying to validate the form input data using javascript. But in js I can't get the form data. while I tried to see the form data using console.log() function it gives undefined.
Here is my form
<form class="cd-signin-modal__form" action="{{ url('/signup') }}" method="POST" id="appointment-form">
{{ csrf_field() }}
<p class="cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--username cd-signin-modal__label--image-replace" for="signup-username" id="name" >Name</label>
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-username" type="text" placeholder="Name" name="reg_name">
</p>
<p class="cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signup-email" id="email">E-mail</label>
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-email" type="email" placeholder="E-mail" name="reg_email">
</p>
<p class="cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--password cd-signin-modal__label--image-replace" for="signup-password" id="password">Password</label>
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-password" type="text" placeholder="Password" name="reg_password">
</p>
<p class="cd-signin-modal__fieldset">
<label class="cd-signin-modal__label cd-signin-modal__label--password cd-signin-modal__label--image-replace" for="signup-password">Role</label>
<select class="form-control searchField" id="service_id_search" name="reg_role_id">
<option value=" ">Select One</option>
#if($_SESSION['role_data'] != null)
#foreach($_SESSION['role_data'] as $data)
<option value="{{ $data->id }}">{{ $data->name }}</option>
#endforeach
#endif
</select>
</p>
<p class="cd-signin-modal__fieldset">
<button id="signup" class="btn btn-secondary btn-lg" type="submit" value="Create account" style="padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;">Create account
</button>
</p>
</form>
Here is the scripts
$(document).ready(function(){
$('#signup').click(function(event){
var name = $('#reg_name').val();
var email = $('#reg_email').val();
var password = $('#reg_password').val();
var role_id = $('#reg_role_id').find(":selected").val();
console.log(name);
console.log(email);
console.log(password);
console.log(role_id);
});
});
Why it gives undefined !!
Anybody help please ?
You are selecting form fields by ID but your none of your fields have such IDs and it seems that you are confusing input name and id properties. For example, for field
<input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-username" type="text" placeholder="Name" name="reg_name">
you need to use its ID with jquery # selector and that is signup-username not reg_name:
var name = $('#signup-username').val();
You are trying to access your elements by using their name attribute with an id (#) selector.
$(document).ready(function(){
$('#signup').click(function(event){
var name = $('#signup_username').val();
var email = $('#signup_email').val();
var password = $('#signup_password').val();
var role_id = $('#service_id_search').find(":selected").val();
console.log(name);
console.log(email);
console.log(password);
console.log(role_id);
});
});
It seems like you have an error on the jquery selector.
$('#thisIstheIdAtrributeValue');
$('#signup').click(function(event){
var name = $('#signup-username').val();
var email = $('#signup-email').val();
var password = $('#signup-password').val();
var role_id = $('#service_id_search').find(":selected").val();
console.log(name);
console.log(email);
console.log(password);
console.log(role_id);
});
$(document).ready(function(){
$('#signup').click(function(event){
var name = $('input[name=reg_name]').val();
var email = $('input[name=reg_email]').val();
var password = $('input[name=reg_password]').val();
var role_id = $('input[name=reg_role_id]').find(":selected").val();
console.log(name);
console.log(email);
console.log(password);
console.log(role_id);
});
});
Related
I am trying to change (div.class=loguser)'s innerhtml to the username that has logged in. To get the username, I wrote a function that gets input of username and password from the register_button which is inside (div#register). I wrote an object(addData) which takes the username and password and stores it in an array(datas). After putting it in the array, I made a function where it verifies if the username and password exists in the array. If it does exist, it is suppose the change the innerhtml to the username. But it is not working. And I cant even submit the form while registering.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(username, password) {
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
for (var i = 0; i < datas.length; i++) {
if (datas[i].username === username &&
datas[i].password === password) {
var name = username;
document.getElementsByClassName('loguser').innerHTML = username;
}
}
}
<body>
<div class="loguser">
<td>
<ul class="nav-area">
<li class="dropdown">User
</li>
</ul>
</td>
</div>
</tr>
</table>
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
isUserValid() shouldn't take username and password as parameters, since it gets them from the inputs. It should take an event parameter, so you can call it as an event listener.
document.getElementsByClassName() returns a NodeList. You need to use [0] to access the first match to set its innerHTML. You could also use document.querySelector(), it just returns the first match.
The login button doesn't have an ID. Add id="login_button" so you can add an event listener to it.
Instead of your loop you can use the find() method to search an array.
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
I have input tags in an HTML page and I want to connect those with form fields
I have linked forms with a model to save the details in the database. when I am adding signup-form as a parameter in return, the model is displaying its own form and my own form is also displaying. I want the code to connect my Html form with the Django form using the name attribute
login.html
<form method = "POST" enctype="multipart/form-data" id="register" class="input-group-register needs-validation" novalidate oninput='up2.setCustomValidity(up2.value != up.value ? "Passwords do not match." : "")'>
<!-- {{ signup_form.as_p }} -->
{% csrf_token %}
<input type="text" class="input-field" id="firstname" placeholder="First Name" name = "first_name" required>
<div class="invalid-feedback">Please enter a valid first name.</div>
<input type="text" class="input-field" id="lastname" name = "last_name" placeholder="Last Name" required>
<div class="invalid-feedback">Please enter a valid last name.</div>
<input type="email" class="input-field" id="email" name = "emailid" placeholder="Email" required>
<div class="invalid-feedback">Please enter a valid Email Address.</div>
<input type="number" class="input-field" id="mobile" name = "number" placeholder="Mobile" required>
<div class="invalid-feedback">Please enter your Mobile Number.</div>
<input type="password" class="input-field" id="password" placeholder="Enter Password" name="up" required>
<div class="invalid-feedback">Please enter your password.</div>
<input type="password" class="input-field" id="confirmpassword" placeholder="Confirm Password" name="up2" required>
<div class="invalid-feedback">Password doesn't match.</div>
<input type="checkbox" class="check-box" required> <span> I agree to the Terms & Conditions </span>
<div class="invalid-feedback">You must agree before submitting.</div>
<button type="submit" name = "submit" class="submit-btn" value="checkform1"> SignUp </button>
</form>
views.py
def user_login(request):
if request.method=='POST':
register_status = False
if request.POST.get('submit') == 'checkform1':
return render(request,'first_app/Login.html')
forms.py
class SignupForm(forms.ModelForm):
class Meta:
model = FormSl
fields = '__all__'
widgets = {
'up' : forms.PasswordInput(),
'up2' : forms.PasswordInput()
}
models.py
class FormSl(models.Model):
# for signup and login
first_name = models.CharField(max_length= 32, unique = True)
last_name = models.CharField(max_length= 32, unique = True)
emailid = models.EmailField()
number = models.IntegerField()
up = models.CharField(max_length = 32, unique = True)
up2 = models.CharField(max_length = 32, unique = True)
def __str__(self):
return self.first_name
You can use jquery for that. Jquery has prepend() method for that. You can move this fields to input's container p element and show in there. Also you can use help_text field option in django for your forms.
There is a discovery.html file that links to a validate_signup.php file through action in the html form. When in the I am in the validate_signup.php and try to retrieve the values with $_POST['XXX'] of the text fields in the form namely regFName, regSName, regEName, regPName it returns an error that states undefined index XXX.
File directory(not sure if it could play a part)
Folder-- HTML, PHP, ect
HTML-- discovery.html, ect
PHP-- validate_signup.php, ect
I create an other html and php file that works similarly and in this example it worked.
HTML FROM:
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" methode="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName"required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para" ></span>
</div>
</form>
PHP:
$password = $_POST["regPName"];
$email = $_POST["regEName"];
$surname = $_POST["regSName"];
$firstname = $_POST["regFName"];
JS-validate data
var error="";
var name = document.getElementById( "regFName" );
if(valPass() == false)
{
error = "Password must contain an UpperCase, LowerCase, Number and Symbol character";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
var email = document.getElementById( "regEName" );
if( email.value == "" || email.value.indexOf( "#" ) == -1 )
{
error = " You Have To Write Valid Email Address. ";
document.getElementById( "error_para" ).innerHTML = error;
return false;
}
else
{
return true;
}
the correct method not methode
<form class="modal-content animate" onsubmit="return validate();" action="../PHP/validate-signup.php" method="post">
<div class="containerL">
<label><b>First name</b></label>
<input type="text" class="LoginFromPage" id="regFName" placeholder="Enter Frist name" name="regFName" required>
<label><b>Surname</b></label>
<input type="text" class="LoginFromPage" id="regSName" placeholder="Enter Surname" name="regSName" required>
<labelb>Email</b></labelb>
<input type="text" class="LoginFromPage" id="regEName" placeholder="Enter Email" name="regEName" required>
<label><b>Password</b></label>
<input type="password" id="regPName" placeholder="Enter Password" name="regPName" required>
<button type="submit">Register</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" id="cancelbtn">Cancel</button>
<div id="error_para"></span>
</div>
</form>
recently started to deal with javascript, now I'm doing a registration page. And at the moment the notification about the incorrect filling of the form is displayed via alert (). How can this be improved so that if you enter incorrectly, you immediately see a hint ?
function valid(form){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker = "Wrong first name";
}else if(!namePattern.test(lName)){
checker = "Wrong last name"
}else if(!passwordPattern.test(password)){
checker = "Wrong password"
}else if(confirmPassword != password){
checker = "Your passwords do not match"
}else if(!emailPattern.test(email)){
checker = "Wrong email"
}
if(checker){
alert(checker);
}
}
<form action="" method="post" name="submit" onsubmit="valid(this)">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<input type="submit" name="submit" value="submit"/>
</form>
I will be grateful for help)
I suggest you put on input elements onchange function, for example:
<input type="text" name="fName" id="fName" placeholder="Your first name" onchange='validateInput(e)'>
And then you check in function:
function validateInput(e){
var namePattern = new RegExp("^([A-z]{4,20})$");
const value = e.target.value;
if(!namePattern.test(value)){
alert("Wrong first name");
// But instead of alert I would suggest you change the color of the input element in order for the user to see real time that he is entering wrong thing.
//When he enters correct data, input border should be green. This is much more user friendly
}
}
You can every validation check separately like this...
function firstname(value){
var checker = false;
var namePattern = new RegExp("^([A-z]{4,20})$");
if(!namePattern.test(value)){
checker = "Wrong first name";
}
if(checker){
alert(checker);
}
}
<input type="text" name="fName" id="fName" placeholder="Your first name" onblur="firstname(this.value)">
I suggest you can use jquery validation.
The thing is, you are checking your form on your submit event (which is obviously the event that is trigger when the form is submitted).
You need to add input validation on each of your input fields via certain event listeners.
If you add onchange event listener, your callback validation will fire each time you move your focus to another element (aka blur event).
If you add oninput event listener, your callback validation will fire each time you type something new.
I would recommend taking a look at the answers of this question.
var checker;
function valid(form){
checker = '';
var namePattern = new RegExp("^([A-z]{4,20})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var fName = form.fName.value;
var lName = form.lName.value;
var password = form.password.value;
var confirmPassword = form.confirmPassword.value;
var email = form.eMail.value;
if(!namePattern.test(fName)){
checker += "No first name<br/>";
}
if(!namePattern.test(lName)){
checker += "No last name<br/>"
}
if(!passwordPattern.test(password)){
checker += "No password<br/>"
}
if(confirmPassword != password){
checker += "Your passwords do not match<br/>"
}
if(!emailPattern.test(email)){
checker += "No email<br/>"
}
if(checker){
document.getElementById("hint").innerHTML = checker;
}
}
valid(document.getElementById("form"));
<form id='form' action="return false;" method="post" name="submit" oninput="valid(this)" onsubmit=' return false;'>
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" placeholder="Your last name">
</div>
<div>
<span>Email Address<label>*</label></span>
<input type="text" name="eMail" placeholder="You email">
</div>
<div class="clear"></div>
<a class="news-letter" href="#">
<label class="checkbox"><input type="checkbox" name="checkbox" checked=" "><i> </i>Sign
Up for Newsletter</label>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<input type="password" name="password" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<input type="password" name="confirmPassword" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div style='color:red' id='hint'></div>
<input type='submit'/>
</form>
Using the oninput event to run every single time a input is changed. More user friendly by displaying a text tip instead of popups, and shows all errors, not just the first one in the if/elseif loop.
P.S: You seem to have forgotten to add the submit button in your code.
EDIT: Also made it check validation as soon as the page loaded up too.
I have been learning javascript by building some mockup website while doing so an error popped up where the form elements are not getting stored to my javascript variables.I have inserted my HTML code of modal dialog box that contains the form and the JS code.Can anyone suggest me where I am going wrong?
document.getElementById("sub").addEventListener("click",store());
function store(){
var userName = document.getElementById("nme").value;
var emailId = document.getElementById("mail").value;
var password = document.getElementById("pd").value;
var rpassword = document.getElementById("rpd").value;
console.log(userName);
if (password !== rpassword){
alert("your password doesn't match");
}
else{
localStorage.setItem("name",userName.value);
localStorage.setItem("email",emailId.value);
localStorage.setItem("password",password.value);
}
}
<div class=row>
<form class="col-xs-12" method="post">
<div class="form-group">
<input type="text" class="form-control form-design input-lg enable" id="nme" name="user" placeholder="UserName">
<input type="text" class="form-control input-lg enable" id="mail" name="mail" placeholder="Email-Id">
</div>
<div class="form-group">
<input type="password" class="form-control form-design input-lg enable" id="pd" name="pwd" placeholder="Password">
<input type="password" class="form-control input-lg enable" name="rpwd" id="rpds" placeholder="Retype Password">
<input type="submit" id="sub" class="btn btn-block btn-lg navi-style lnk" value="SignUp">
</div>
</form>
</div>
<footer class="align">Already a member?<a class="newlnk" data-toggle="modal" href="#login">SignIn</a>
</footer>
</div>
<!--body closed-->
</div>
<!--content closed-->
</div>
<!--Dialog box closed-->
</div>
<!--Model closed-->
</div>
<!--container closed-->
The variables to store should be of type string i.e. var userName should already be a string, so storing userName.value will result in trying to store 'undefined', hence the correct values to store should be the var without the 'value' property and one of your element ids is misspeled i.e.
var rpassword = document.getElementById("rpds").value;
.
e.g. try the following code instead of the current store function
function store(){
var userName = document.getElementById("nme").value;
var emailId = document.getElementById("mail").value;
var password = document.getElementById("pd").value;
var rpassword = document.getElementById("rpds").value;
console.log(userName);
if (password !== rpassword){
alert("your password doesn't match");
}
else{
localStorage.setItem("name",userName);
localStorage.setItem("email",emailId);
localStorage.setItem("password",password);
}
}
You are trying to store userName.value instead of userName (and so on).
Also, you add an event listener but actually call the function store instead of referencing it.
document.getElementById("sub").addEventListener("click",store);
function store(){
var userName = document.getElementById("nme").value;
var emailId = document.getElementById("mail").value;
var password = document.getElementById("pd").value;
var rpassword = document.getElementById("rpd").value;
console.log(userName);
if (password !== rpassword){
alert("your password doesn't match");
}
else{
localStorage.setItem("name",userName);
localStorage.setItem("email",emailId);
localStorage.setItem("password",password);
}
}