Javascript Simplification - Onclick, Onblur, Onfocus - Forms - javascript

Is there a way to simplify my javascript code below?
It works but I am quite sure that there must be a way to reduce what evidently shows my elementary javascript skills, and of course, I am trying to improve my understanding.
My HTML Code is just a simple form:
<div>
<form action="">
<input type="text" name="firstname" id="un1" value="First Name"/>
<input type="text" name="surname" id="un2" value="Surname" />
<input type="text" name="username" id="un3" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
My Javascript Code (unobtrusive):
window.onload = function(){
//Field Manoeuvre1
document.getElementById("un1").onclick = fieldClear1;
document.getElementById("un1").onfocus = fieldClear1;
document.getElementById("un1").onblur = fieldReplace1;
//Field Manoeuvre2
document.getElementById("un2").onclick = fieldClear2;
document.getElementById("un2").onfocus = fieldClear2;
document.getElementById("un2").onblur = fieldReplace2;
//Field Manoeuvre3
document.getElementById("un3").onclick = fieldClear3;
document.getElementById("un3").onfocus = fieldClear3;
document.getElementById("un3").onblur = fieldReplace3;
}
//Field Manoeuvre1
function fieldClear1(){
if(document.getElementById("un1").value == "First Name"){
document.getElementById("un1").value = "";
}
}
function fieldReplace1(){
if(document.getElementById("un1").value == ""){
document.getElementById("un1").value = "First Name";
}
}
//Field Manoeuvre2
function fieldClear2(){
if(document.getElementById("un2").value == "Surname"){
document.getElementById("un2").value = "";
}
}
function fieldReplace2(){
if(document.getElementById("un2").value == ""){
document.getElementById("un2").value = "Surname";
}
}
//Field Manoeuvre3
function fieldClear3(){
if(document.getElementById("un3").value == "Email Address"){
document.getElementById("un3").value = "";
}
function fieldReplace3(){
if(document.getElementById("un3").value == ""){
document.getElementById("un3").value = "Email Address";
}
}

SOLUTION 1:
HTML:
<div>
<form action="">
<input type="text" name="firstname" id="un1" class="myInput" value="First Name"/>
<input type="text" name="surname" id="un2" class="myInput" value="Surname" />
<input type="text" name="username" id="un3" class="myInput" value="Email Address"/>
<input type="button" value="Register!" />
</form>
</div>
JS:
var defaultValues = {
un1 : 'First Name',
un2 : 'Surname',
un3 : 'Email Address'
}
var elements = document.querySelectorAll('.myInput');
for (var i=0; i<elements.length; i++) {
elements[i].addEventListener(['click', 'focus'], function(){
if (this.value === defaultValues[this.id]) this.value = '';
});
elements[i].addEventListener('blur', function(){
if (this.value === '') this.value = defaultValues[this.id];
});
}
PS: The code is not compatible with all browsers. If you aim for browser compatibility, you should probably use a library that abstracts away the differences (ex: jQuery).
SOLUTION 2:
No change in HTML
JS:
window.onload = function(){
var field;
//Field Manoeuvre1
field = document.getElementById('un1');
field.onclick = fieldClear.bind(field, 'First Name');
field.onfocus = fieldClear.bind(field, 'First Name');
field.onblur = fieldReplace.bind(field, 'First Name');
//Field Manoeuvre2
field = document.getElementById('un2');
field.onclick = fieldClear.bind(field, 'Surname');
field.onfocus = fieldClear.bind(field, 'Surname');
field.onblur = fieldReplace.bind(field, 'Surname');
//Field Manoeuvre3
field = document.getElementById('un3');
field.onclick = fieldClear.bind(field, 'Last Name');
field.onfocus = fieldClear.bind(field, 'Last Name');
field.onblur = fieldReplace.bind(field, 'Last Name');
}
function fieldClear(value){
if(this.value === value) this.value = '';
}
function fieldReplace(value){
if(this.value === '') this.value = value;
}
DEMO: http://jsbin.com/ekoJuQE/1/edit

Use either jquery or html5
Html5 solution:
Add parameter placeholder to input like this
<input name="firstname" type="text" placeholder="First name" />
Jquery (plus attribute data-placeholder="text shown in field" on html input fields:
$(window).on("load", function(){
$("#un1, #un2, #un3").on("click, focus", fieldClear(this));
$("#un1, #un2, #un3").on("blur", fieldReplace(this));
});
function fieldClear(obj) {
$(obj).val('');
}
function fieldReplace(obj) {
$(obj).val($(obj).data('placeholder'));
}

Delegated event handling can shorten things up a bit. If you pick up jQuery, then add classes or select by element type. Also add a data attr.
<input type="text" name="surname" id="un2" value="Surname" data-placeholder="Surname"/>
$('form').on('click, focus', 'input', function(e){
$(this).val("");
});
$('form').on('blur', 'input', function(){
$(this).val($(this).attr('data-placeholder'));
});

Related

Why the paragraphs arent showing up when inputs are empty

im pretty new to coding and i wanted to try to make a register form and use javascript to check if any of the forms are empty. I tried to make it using DOM but it seems that its not working. If anyone can help me i will be really thankful.
js code:
let btnCheck = document.querySelector('#claim');
let input = document.querySelectorAll('input');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
function checkForBlank(){
if (document.querySelector('#fname').value == ""){
fname.innerHTML = 'First Name cannot be empty'
}
if (document.querySelector('#lname').value == ""){
lname.innerHTML = 'Last Name cannot be empty'
}
if (document.querySelector('#email').value == ""){
email.innerHTML = "Looks like this is not an email"
}
if (document.querySelector('#password').value ==""){
password.innerHTML = 'Password cannot be empty'
}
}
btnCheck.addEventListener('click', checkForBlank());
html code:
<form>
<input type='text' placeholder="First Name">
<p id='fname'></p>
<input type='text' placeholder="Last Name">
<p id='lname'></p>
<input type='text' placeholder="Email Address">
<p id='email'></p>
<input type='password' placeholder="Password">
<p id='password'></p>
</form>
Your code does not check to see if the form input field is empty currently. You would want to get reference to the input and check to see if that is empty.
<form>
<input id="fname-input" type="text" placeholder="First Name" />
<p id="fname"></p>
<input id="lname-input" type="text" placeholder="Last Name" />
<p id="lname"></p>
<input id="email-input" type="text" placeholder="Email Address" />
<p id="email"></p>
<input id="password-input" type="password" placeholder="Password" />
<p id="password"></p>
</form>
const btnCheck = document.querySelector('#claim');
const fname = document.querySelector('#fname');
const fnameInput = document.querySelector('#fname-input');
const lname = document.querySelector('#lname');
const lnameInput = document.querySelector('#lname-input');
const email = document.querySelector('#email');
const emailInput = document.querySelector('#email-input');
const password = document.querySelector('#password');
const passwordInput = document.querySelector('#password-input');
function checkForBlank() {
if (fnameInput.value == "") {
fname.innerHTML = "First Name cannot be empty";
}
if (lnameInput.value == "") {
lname.innerHTML = "Last Name cannot be empty";
}
if (emailInput.value == "") {
email.innerHTML = "Looks like this is not an email";
}
if (passwordInput.value == "") {
password.innerHTML = "Password cannot be empty";
}
}
btnCheck.addEventListener('click', checkForBlank);
Additionally, you need to pass a function reference to addEventListener instead of invoking the function.
btnCheck.addEventListener('click', checkForBlank()); // WRONG
btnCheck.addEventListener('click', checkForBlank); //RIGHT
Note: I would recommend to rather (or additionally) use the required property of html elements https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required
There are multiple things that you need to refactor
It would be better to create a new HTML element for errors with different classes.
As you are wrapping the inputs in the form element, So you need to preventDefault.
For clickListener you need to pass the function reference only, no need to execute the function
// INPUTS
let btnCheck = document.querySelector('#claim');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
// INPUT ERRORS
let fnameError = document.querySelector('#fname-error');
let lnameError = document.querySelector('#lname-error');
let emailError = document.querySelector('#email-error');
let passwordError = document.querySelector('#password-error');
function checkForBlank(e) {
e.preventDefault();
console.log(fname.value);
if (fname.value === "") {
fnameError.textContent = 'First Name cannot be empty'
} else {
fnameError.textContent = ''
}
if (lname.value === "") {
lnameError.textContent = 'Last Name cannot be empty'
} else {
lnameError.textContent = ''
}
if (email.value === "") {
emailError.textContent = "Looks like this is not an email"
} else {
emailError.textContent = ''
}
if (password.value === "") {
passwordError.textContent = 'Password cannot be empty'
} else {
passwordError.textContent = ''
}
}
btnCheck.addEventListener('click', checkForBlank);
p.error{
color: red;
font-size: 12px;
padding: 0;
margin: 4px 0 8px 0;
}
<form>
<input type='text' placeholder="First Name" id='fname'>
<p class="error" id="fname-error"></p>
<input type='text' placeholder="Last Name" id='lname'>
<p class="error" id="lname-error"></p>
<input type='text' placeholder="Email Address" id='email'>
<p></p>
<p class="error" id="email-error"></p>
<input type='password' placeholder="Password" id='password'>
<p></p>
<p class="error" id="password-error"></p>
<button id="claim"> check </button>
</form>

How can I verify form passwords match using JavaScript?

I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>

Disable Button for form

I have a simple form. Ive tried to disable the the submit button until fields have been filled out, however it seems to not be working. can anyone point me in the right direction to what I'm doing wrong.
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userName" class="inputs"><br>
Text: <input type="name" id="userName" class="inputs"><br>
<input type="submit" id="userSubmit" disabled><br>
</form>
<div id='alertMessage'></div>
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "")
{
alertMessage.innerHTML = 'Please fill in form correctly';
userSubmit.disabled = true;
return false;
} else {
alertMessage.innerHTML = 'Thank you for filling in form';
userSubmit.disabled = false;
return true;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
Your main issue is that you have used the same id on more than one element. ids must be unique within a document.
Also, return false is not doing anything for you in this context.
Lastly, don't use .innerHTML when you aren't supplying any HTML, use textContent for that instead.
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "") {
alertMessage.textContent = 'Please fill in form correctly';
userSubmit.disabled = true;
} else {
alertMessage.textContent = 'Thank you for filling in form';
userSubmit.disabled = false;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userEmail" class="inputs"><br>
Text: <input type="name" id="userText" class="inputs"><br>
<input type="submit" id="userSubmit" disabled>
</form>
<div id='alertMessage'></div>

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

Displaying range validator error message on html input

I have an input type =text in html and i have this js code in js file to show error message
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
var toReturn = 0;
$("input", $form).each(function () {
if ($(this).val() == "") {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = 1;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
I am trying to convert this code to make range validator on input type=text field .dispalying only 5 digits in the textbox, but i couldn't achieve . Is there any easy way to do this ?
Thanks
Consider using the jQuery validation plugin instead, especially the rangelength method for your case. However, if you want to stick to the original code without using any library then I suggest you try the code below for example:
HTML:
<form id="myid" name="myid" method="post" action="/">name :
<input type="text" name="name" id="name" />age :
<input type="text" name="age" id="age" />
<input type="submit" id="submit" name="submit" value="Save" />
</form>
jQuery:
var $form = $("#myid"),
$errorMsg = $("<span id='myerrormessagespan' class='error' style='color:red;'>*</span>");
$("#submit").on("click", function () {
var toReturn = true;
$("input", $form).each(function () {
var value = $(this).val();
if((!$.trim(this.value).length) || (value.length > 5)) {
if (!$(this).data("error")) {
$(this).data("error", $errorMsg.clone().insertAfter($(this)));
}
toReturn = false;
}
else {
if ($(this).data("error")) {
$(this).data("error").remove();
$(this).removeData("error");
}
}
});
return toReturn;
});
Working JSFiddle Demo

Categories

Resources