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);
}
}
Related
I am creating a simple login an sign up form that is used to create a user and store it in the local host. I have got the sign up form working as it should, but when I try and pull the information from the localhost, it just refreshes the page. Im just wondering how I can get the function to work correctly.
Here is my JS:
const signup = (e) => {
let user = {
firstName: document.getElementById("firstName").value,
lastname: document.getElementById("lastName").value,
email: document.getElementById("email").value,
username: document.getElementById("username").value,
password: document.getElementById("password").value,
confirm_password: document.getElementById("confirm_password").value,
};
localStorage.setItem("user", JSON.stringify(user));
console.log(localStorage.getItem("user"));
e.preventDefault();
alert("Signup Successful")
};
function login() {
var stored_username = localStorage.getItem('username');
var stored_password = localStorage.getItem('password');
var username1 = document.getElementById('username1');
var password2 = document.getElementById('password2');
if(username1.value == stored_username && password2.value == stored_password) {
alert('Login Successful.');
}else {
alert('Username or password is incorrect.');
}
}
document.getElementById("login-btn").addEventListener(type = click, login())
And here is my HTML:
<div class="bodyBx">
<section>
<div class="container">
<div class="user signinBx">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1551034549-befb91b260e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form>
<h2>Sign In</h2>
<input type="text" id="username2" placeholder="Username" />
<input type="password" id="password2" placeholder="Password" />
<button id = "login-btn" type="submit" onclick="login();">Submit</button>
<p class="signup">
Need an account ?
Sign Up.
</p>
</form>
</div>
</div>
</div>
</section>
<!-- ================= Sign Up Form Start ================= -->
<section>
<div class="container">
<div class="user signupBx" id="section2">
<div class="imgBx"><img src="https://images.unsplash.com/photo-1555680206-9bc5064689db?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" style="width: 400px;" alt="" /></div>
<div class="formBx">
<form role="form" onsubmit="signup(event)">
<h2>Sign Up</h2>
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<input type="email" id="email" placeholder="example#email.com..." />
<input type="text" id="username" placeholder="Username" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirm_password" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
</section>
</div>
Change the type of login button to button from submit, like below
<button id = "login-btn" type="button" onclick="login();">Submit</button>
If type=submit the form is posted to the url specified in the action attribute of the form, else to the same page if action is missing and you will see a page refresh.
Alternate method - You can also try return false; in your login()
Also your addEventListener should be like below, you don't have to provide type = click, the first param is of type string and second param is of type function. Check docs
document.getElementById("login-btn").addEventListener("click", login)
Localstorage can only store text. So you store a stringified object, which is fine, but you're trying to retrieve properties from it which don't exist.
Instead of:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
localStorage.getItem("someField");
//localstorage doesnt know what someField is
You want:
var itm={someField:1};
localStorage.setItem("itm",JSON.stringify(itm));
//then later
itm = JSON.parse(localStorage.getItem("itm"));
someField = itm.someField
As for the refresh, check this out:
Stop form refreshing page on submit
TL;DR: Add e.preventDefault() in function login() (you'll have to change it to function login(e).
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 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);
});
});
I failed asking this as my first question, hope this I do better.
"I just learned the basics of HTML/CSS but have almost to no idea of javascript. And I am making a website where I have a password box with a link button(disabled by default) leading to another page. My struggle is how to make a single password that when entered can enable that button in order to enter the other page. Sorry for my noobish question but am too new in the programming world."
So the html part for what I'm trying to do is:
<div class="whole">
<div>
<input type="password" placeholder="PASSWORD" required id="password" class="pass">
</div>
<div>
<a href="link">
<button class="button" id="button" type="submit" disabled>Click me!!!</button>
</a>
</div>
</div>
And all that I could do by research and on my own with the script was:
<script>
var pass1 = "pass";
var pass2 = document.getElementById("password");
if (pass1 == pass2) {
document.getElementById("button").disabled = false;
}
</script>
Sorry for my clumsiness again!
Thank you!!! :)
<div class="whole">
<div>
<input type="password" placeholder="PASSWORD" required id="password" onkeyup="check()" class="pass">
</div>
<div>
<a href="link">
<button class="button" id="button" type="submit" disabled="true">Click me!!!</button>
</a>
</div>
</div>
<script type="text/javascript">
var pass1 = "pass";
function check(){
var pass2 = document.getElementById("password").value;
if (pass1 == pass2) {
document.getElementById("button").disabled = false;
}
}
I created a fiddle , check it, I hope it will work
https://jsbin.com/qozawoj/edit?html,js,output
<div class="whole">
<div>
<input type="password" placeholder="PASSWORD" required id="password" class="pass" onkeyup="check()">
</div>
<div>
<button class="button" id="button" type="submit" onclick="go()" disabled="true">Click me!!!</button>
</div>
</div>
JS
var pass1 = "pass";
var pass2 = document.getElementById("password");
function check(){
if (pass1 == pass2.value) {
document.getElementById("button").disabled = false;
}
}
function go (){
alert('go');
}
You are close and you need a few more things.
Checkout the code below with // inline comments:
function myCheck(){ // called everytime password is entered
var pass1 = "pass";
var pass2 = document.getElementById("password").value; // you missed "value" !
if (pass1 == pass2) {
document.getElementById("button2").disabled = false; // enable link here
}
}
<div class="whole">
<div>
<input type="password" placeholder="PASSWORD" required id="password" class="pass" onkeyup="myCheck()"> <!-- myCheck() is called everytime the keyboard key goes from down to up -->
</div>
<div>
<a id="button2" href="http://rahul-desai3.github.io/chat/" disabled>button</a> <!-- notice the "disabled" attribute and NO <button> element -->
</div>
</div>
To make the link look like a button, use CSS.
I am creating a form where a user has to fill out several fields and then click sign up. However, I want JavaScript to check if the passwords match, and if they don't or a field is left empty to put the signup button into a disabled state with Bootstrap. However, nothing is working. Here is my code:
JSFIDDLE: http://jsfiddle.net/jbe65/
echo '
<h3>Don\'t have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<br><br>
<p id="submit">button class="btn btn-primary btn-block" type="submit">Sign Up/button></p>
</form>
<script>
var empty = "";
var email = $(\'#email\').val()\;
var pass = $(\'#pass\').val()\;
var passver = $(\'#passver\').val()\;
if (empty == email)
{
if (pass != passver)
{
document.getElementById("submit").innerHTML=\'<button class="btn btn-primary btn-block" type="submit" disabled="disabled">Sign Up</button>\';
}
}
</script>
';
I will suggest make the button lookalike disable (by css) and once all the cond pass can make it enable (by css)..
$(document).ready(function () {
$("#formid").on("submit", function (e) {
var empty = "";
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if (empty == email || pass !== passver)
{
alert("please enter valid email and password.");
e.preventDefault();
}
else
{
//u can call this in textbox blur also...
$("#sub").removeClass("disable");
}
});
});
Fiddle Demo
I'm assuming you are using PHP. If so, you can replace the echo statement with a closing PHP bracket ?> to escape the parser. It's generally easier to deal with.
To answer the question at hand, since you are using jQuery, there is no need to change the innerHTML of the p tag, just use the .prop() function, like so:
?>
<h3>Don't have an account yet? Sign up now!</h3>
<form action="signup.php" method="post">
<input type="text" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass">
<input type="password" class="form-control" placeholder="Again" name="passver" id="passver">
<p id="submit"><button class="btn btn-primary btn-block" type="submit">Sign Up</button></p>
</form>
<script>
var email = $('#email').val();
var pass = $('#pass').val();
var passver = $('#passver').val();
if ("" == email)
{
if (pass != passver)
{
$('#submit button').prop('disabled', true);
}
}
</script>
<?php
If you're using HTML5 , Put "Required" and then the submit button will not be loaded if there is an empty field Ex :