Validating Form with Javascript (Simple Test) - javascript

var name = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (name.value == '') {
alert('test');
}
}
I was simply trying to make sure everything was working before I began learning actual client-side validation.
Here is the HTML
<form role='form' name='contactForm' action='#' method="POST" id='contact-form'>
<div class="form-group">
<label for="contact-name">First and Last Name</label>
<input type="text" class="form-control" id="contact-name" name="contactName" placeholder="Enter your name.." pattern="[A-Za-z]+\s[A-Za-z]+">
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contactEmail" name="contactEmail" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="number" class="form-control" id="contactPhone" name="contactPhone" placeholder="Enter Phone Number" required'>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" placeholder="Enter a brief message" name='contactMessage' id='contact-message' required></textarea>
</div>
<input type="submit" class="btn btn-default" value='Submit' onclick='checkForm()'>
</fieldset>
</form>
I took the required attribute off, and if I leave the name field empty it goes right to the other one when i click submit. To check whether javascript was working at all, i did an basic onclick function that worked.
Maybe someone can explain to me what is wrong with the checkForm function. Thanks in advance.
P.S The form-group and form-control classes belong to bootstrap

Change your javascript to this:
var contactName = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (contactName.value === '') {
alert('test');
}
}

Okay, Hobbes, thank you for editing your question, now I can understand your problem.
Your code faces three two issues.
Your control flow. If you want to validate your field, you have to obtain its value upon validation. You instead populate variable name when the page loads, but the user will enter the text only after that. Hence you need to add var someVariableName = document.getElementById(...); to the beginning of the checkForm() function.
global variables. Please do not use them like that, it is a good design to avoid global variables as much as possible, otherwise you bring upon yourself the danger of introducing side effects (or suffering their impact, which happens in your situation). The global context window already contains a variable name and you cannot override that. See window.name in your console. You can of course use var name = ... inside the function or a block.
Even if you fix the above, you will still submit the form. You can prevent the form submission if you end your checkForm() function with return false;
For clarity I append the partial javascript that should work for you:
function checkForm() {
var name = document.getElementById('contact-name');
if (name.value == '') {
alert('test');
return false;
}
}
EDIT: As Eman Z pointed out, the part 1 of the problem does not really prevent the code from working as there's being retrieved an address of an object (thanks, Eman Z!),

Related

onclick function getInc not defined

I am creating my first web app and have run in to an issue pretty early on!
I have created a function which extracts the information that the user keys into the HTML input field. The way it should work is that when the user enters their income and clicks the submit button, the income is stored in a variable for me to use throughout the rest of my JavaScript code.
Looking at the console log, the function is coming up as 'not defined'.
I appreciate the code is probably not very clean but I just want to get it working as it's my first small project!
Any ideas where I am going wrong?
Here's the HTML:
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit" onclick="getInc();">
</div>
Here's the JavaScript:
function getInc() {
var inc = document.getElementById("Ann-Sal");
}
I remove semiclon from onclick end and it works
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit" onclick="getInc()">
</div>
<script>
function getInc() {
console.log('works');
var inc = document.getElementById("Ann-Sal");
}
</script>
<script>
function getInc() {
console.log('works');
var inc = document.getElementById("Ann-Sal");
}
</script>
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit" onclick="getInc()">
</div>
First of all make sure you have your <script> after the body (ie: put it after the last closing <div>), secondly if you want to what the user typed in you should get the elements value. When you set inc equal to document.getElementById("Ann-Sal"); you are giving it the DOM element instead of the it's value instead you should put:
function getInc() {
var inc = document.getElementById("Ann-Sal");
}
Then you will get the value the user inputted to the code.
Also, a tip use addEventListener() instead of the onclick attribute, it's better practice.
Ok, so I tried to fix it myself using some of Tom O's code above here:
var buttonEl = document.querySelector('input[type="button"]');
var inputEl = document.getElementById("Ann-Sal");
var annInc;
function clickHandler() {
annInc = parseFloat(inputEl.value);
console.log(annInc);
}
buttonEl.addEventListener('click', clickHandler);
HTML:
<div class="row input-1">
<label for="Gross Annual Salary">£</label>
<input type="number" name="Gross Annual Salary" id="Ann-Sal" placeholder="Gross Annual Salary" required>
<input type="button" class="submit-btn" value="Submit">
</div>
This didn't work. There was no error message but nothing was logged to the console when submitting an income into the input field.
I then reconfigured the Javascript code to this:
var buttonEl = document.querySelector('input[type="button"]');
var inputEl = document.getElementById("Ann-Sal");
var annInc;
function clickHandler() {
if (!inputEl.value.length) {
console.error('A salary is required!');
return;
}
annInc = parseFloat(inputEl.value);
console.log(annInc);
}
buttonEl.addEventListener('click', clickHandler);
This then worked. I didn't use the if statement to validate the users input previously because I used 'required' in the input element within my HTML code which basically does the same thing right? So i'm guessing the reason why the code wasn't working because the 'return' statement wasn't used?
Would someone be kind enough to explain to me why the return statement enabled this to work?
I'm sure for some of you experienced guys, my lack of understanding must be painful for you! I am super determined to get my head around this though.
Many thanks
Besides the other answers, I just wanna point it out that is missing the .value in your function, otherwise, you won't get the value.
function getInc() {
var inc = document.getElementById("Ann-Sal").value
}

Trying to verify passwords are matching using html and javascript

I have a form that is supposed to register a user and I have two inputs for passwords that are supposed to be the same. I use html for the form and javascript to check if both inputs are matching. The code I'm using doesn't work though because even if the passwords are different, the user data is still sent to my console when the form shouldn't be able to submit in the first place. These are portions of my html file.
<form id="registration-info" method="POST" action="/registration" onsubmit="return validatePassword();">
....
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password"required>
<script language='javascript' type='text/javascript'>
var password = document.getElementById("password")
, repeat_password = document.getElementById("repeat_password");
function validatePassword(){
if(password.value != repeat_password.value) {
document.repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
</script>
</div>
You have a few mistakes there you'll need to fix up.
Use a JavaScript event listener and remove document..
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
document.repeat_password.setCustomValidity('');
}
}
You do not need to use document. when references variables you have set. Using a JavaScript event listener helps you write clean code, that separates UI and logic.

how to use autocomplete in angularjs

I have an application with add friend feature, in that feature, user must fill their friend's username in the textbox. this is the html code:
<div content-for="title">
<span>Add Friend</span>
</div>
<form class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID">
</div>
<button type="submit" class="btn btn-default" data-ng-click="addfriends()">Add</button>
the interface will be like this
and this is the js code:
// addfriend
$scope.add = {};
$scope.addfriends = function(){
$scope.messages = {
email : $scope.add.email,
userid : $scope.datauser['data']['_id']
};
//event add friend
socket.emit('addfriend',$scope.messages,function(callback){
if(!callback['error']){
$scope.datauser['data']['penddingrequest'].push(callback['data']);
//push pendding request to localstorage user
localStorageService.remove('user');
localStorageService.add('user', $scope.datauser);
$scope.add['email'] = '';
alert('Successfully added friend');
}else{
var msg = callback['error'];
navigator.notification.alert(msg,'','Error Report','Ok');
}
});
};
I want to change this feature little bit, I want to make this textbox showing some suggestion based on the input, like if user input 'a', the textbox will show all user id that start with 'a'. something like twitter's searchbox or instagram searchbox. these user ids is from database.
example searchbox of web instagram
my question is how to change this textbox to be autocomplete but still work like before? thanks very much
There are many ways to do this.
First is this one: You basically create Angular directive for your input.
http://jsfiddle.net/sebmade/swfjT/
Another way to do is to attach onKeyUp event to your input:
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID" ng-keyup="searchFriends()">
<div ng-model="searchFriendsResult" />
</div>
And then, in your controller, you create a searchFriends function that will:
Search your database
Display the result in the view.
Something like this (not a complete code):
$scope.searchFriends = function(value){
// Make Ajax call
var userRes = $resource('/user/:username', {username: '#username'});
userRes.get({username:value})
.$promise.then(function(users) {
$scope.searchFriendsResult = users;
});
};
Use Bootstrap Typeahead
<input type="text" ng-model="asyncSelected"
placeholder="Locations loaded via $http"
uib-typeahead="address for address in getLocation($viewValue)"
typeahead-loading="loadingLocations"
typeahead-no-results="noResults"
class="form-control"/>

How to change button state in javascript

I need to code a function in Javacript that updates the button colour and enables it when all fields are valid.
See picture below to understand the user interaction with the form
When the admin wants to update an user the update button needs to be green only if the following apply
At least one edit button is enabled. (When the edit button is enabled the respective fields is deleted and the user can write something)
The field must be validated in real time
If I uncheck the field the script has to revalidate the other open fields. For Instance if the open field is blank the button should be red but if I close the field and another field was enabled and filled with valid text (lets assume just 1 character means valid) the button from red should turn green
Could you please help me to figure this out. I think a solution is to use the JQuery keyup function but it is restricted only to one field. I need instead something more global.
Is there a way in javascript to create a global button listener than be useful for this scenario
In addition when I turn on the password checkbox two fields are enabled and the button should be valid only if password is valid and it matches with confirmed password
Please see below a brief summary of the jsp page
I have omitted the small icons of the password fields and the bootstrap part of the code
<sf:form class="form-horizontal"
role="form"
id="formsubmit"
method="POST"
action="${pageContext.request.contextPath}/updateprofile"
commandName="user">
<sf:input type="text" class="form-control" value="${user.username}" path="username" readonly="true"></sf:input>
<input type="checkbox" class="form-control" name="email-checkbox" checked />
<sf:input id="emailInput" type="text" class="form-control" path="email" placeholder="Type Email" name="email" disabled="true" />
<input type="checkbox" class="form-control" name="first-name-checkbox" checked />
<sf:input id="nameInput" type="text" class="form-control" placeholder="Type First Name" path="firstName" name="firstName" disabled="true" />
<input type="checkbox" class="form-control" name="last-name-checkbox" checked />
<sf:input id="surnameInput" type="text" class="form-control" placeholder="Type Last Name" path="lastName" name="lastName" disabled="true" />
<input type="checkbox" class="form-control" name="password-checkbox" checked />
<input id="password" type="password" class="form-control" name="password" placeholder="Insert Password" disabled>
<input id="confirmpassword" type="password" class="form-control" name="confirmpassword" placeholder="Confirm Password" disabled>
<button id="updateUserBtn" type="submit" class="btn btn-danger" data-loading-text="Creating User..." disabled>Update User</button>
</sf:form>
My first attemp with javascript is below and it works only for the password fields but it is not connected with the edit button
$("input[type=password]").keyup(
function() {
var ucase = new RegExp("[A-Z]+");
var lcase = new RegExp("[a-z]+");
var num = new RegExp("[0-9]+");
if ($("#password").val().length >= 8) {
$("#8char").removeClass("glyphicon-remove");
$("#8char").addClass("glyphicon-ok");
$("#8char").css("color", "#00A41E");
} else {
$("#8char").removeClass("glyphicon-ok");
$("#8char").addClass("glyphicon-remove");
$("#8char").css("color", "#FF0004");
}
if (ucase.test($("#password").val())) {
$("#ucase").removeClass("glyphicon-remove");
$("#ucase").addClass("glyphicon-ok");
$("#ucase").css("color", "#00A41E");
} else {
$("#ucase").removeClass("glyphicon-ok");
$("#ucase").addClass("glyphicon-remove");
$("#ucase").css("color", "#FF0004");
}
if (lcase.test($("#password").val())) {
$("#lcase").removeClass("glyphicon-remove");
$("#lcase").addClass("glyphicon-ok");
$("#lcase").css("color", "#00A41E");
} else {
$("#lcase").removeClass("glyphicon-ok");
$("#lcase").addClass("glyphicon-remove");
$("#lcase").css("color", "#FF0004");
}
if (num.test($("#password").val())) {
$("#num").removeClass("glyphicon-remove");
$("#num").addClass("glyphicon-ok");
$("#num").css("color", "#00A41E");
} else {
$("#num").removeClass("glyphicon-ok");
$("#num").addClass("glyphicon-remove");
$("#num").css("color", "#FF0004");
}
if ($("#password").val() == $("#confirmpassword").val()
&& ($("#confirmpassword").val() != 0)) {
$("#pwmatch").removeClass("glyphicon-remove");
$("#pwmatch").addClass("glyphicon-ok");
$("#pwmatch").css("color", "#00A41E");
} else {
$("#pwmatch").removeClass("glyphicon-ok");
$("#pwmatch").addClass("glyphicon-remove");
$("#pwmatch").css("color", "#FF0004");
}
if ($("#password").val().length >= 8
&& ucase.test($("#password").val())
&& lcase.test($("#password").val())
&& num.test($("#password").val())
&& $("#password").val() == $("#confirmpassword").val()
&& ($("#confirmpassword").val() != 0)) {
$("#updateUserBtn").removeClass("btn-danger");
$("#updateUserBtn").addClass("btn-success");
$("#updateUserBtn").prop('disabled', false);
} else {
$("#updateUserBtn").removeClass("btn-success");
$("#updateUserBtn").addClass("btn-danger");
$("#updateUserBtn").prop('disabled', true);
}
});
A keyup handler attached to the form element will be called for any field within it having a keyup event. That is because most events bubble up through all their ancestors and can be listened for at any level.
Small example as requested :)
$("form").keyup(
function() {
// your existing code here
});
If you want to target only specific inputs for the changes, you could use a delegated handler instead attached to the form (this one is using the specific form id):
$("#formsubmit").on('keyup', 'input[type=text],input[type=password]',
function() {
// your existing code here
});
This applies the selector at event time so is quite efficient, and also means the this value will be the control that changed (if that is useful to you).
As a general jQuery guideline, only run selectors once and save the element. This is faster & shorter and usually more readable. Also you can chain most jQuery functions together.
e.g.
var $password = $("#password");
var $8char = $("#8char");
if ($password.val().length >= 8) {
$8char.removeClass("glyphicon-remove").addClass("glyphicon-ok").css("color", "#00A41E");

Reset Polymer paper-input-container value and label

I'm having trouble resetting the label inside a paper-input-container after submitting a form. The form is a simple login form. If a user logs in, out, and back in again without a page refresh (from the browser), the label appears to be stuck as if there were a value in the input.
Here's an image to show the difference:
Here's the form inside the element:
<form is="iron-form">
<paper-input-container id="email_container">
<paper-input-error>E-mail or Password is incorrect</paper-input-error>
<label>E-Mail Address</label>
<input is="iron-input" id="email" on-blur="validateEmail" value="{{emailInput::input}}">
</paper-input-container>
<paper-input-container id="password_container">
<label>Password</label>
<input is="iron-input" id="password" type="password" value="{{passwordInput::input}}">
</paper-input-container>
<paper-button raised dialog-dismiss>Cancel</paper-button>
<paper-button raised on-tap="handleCsrf">Login</paper-button>
</form>
These two approaches both get the form to the "after login" state the same:
//
this.emailInput = null;
this.passwordInput = null;
//
this.emailInput = "";
this.passwordInput = "";
I thought this would reset the entire container somehow, but it does nothing:
this.$.email_container = null;
this.$.password_container = null;
iron-input
bindValue
String
Use this property instead of value for two-way data binding.
<paper-input-container id="email_container">
<paper-input-error>E-mail or Password is incorrect</paper-input-error>
<label>E-Mail Address</label>
<input is="iron-input" id="email" on-blur="validateEmail" bind-value="{{emailInput::input}}">
</paper-input-container>
<paper-input-container id="password_container">
<label>Password</label>
<input is="iron-input" id="password" type="password" bind-value="{{passwordInput::input}}">
</paper-input-container>
With bindValue apparently both this.emailInput = null and this.set('emailInput, null) do the trick.
I'm not sure why the first form didn't work (I'm using a paper-input, not iron-input, and it worked there), it's possible the problem is somewhere in the code not shown. But something else to try is directly setting the value:
this.$.email.value = null; // where 'email' is the ID of the iron-input
I'm not entirely sure how this will interact with bind-value, but the docs do say
iron-input adds the bind-value property that mirrors the value
property
You can reset a complete iron-form by calling the reset() method:
document.getElementById('idOfForm').reset();

Categories

Resources