How to make reuse JavaScript function properties using objects - javascript

I'm trying to create HTML elements and it's properties using javascript I need to reuse it in a couple of places without writing repeated same code. FYI below is my code which I'm declaring in the object.
I want to use this code for other elements which contain a label, same classes.
addNewLabels : function(){
var selectnewPwText = document.createElement('LABEL');
selectnewPwText.innerText = "Select label Name";
selectnewPwText.classList.add("mystyle");
document.querySelector('.select-new-password').appendChild(selectnewPwText);
}
var resetPasswordControls = {
passwordBtnInnerText: "Something else",
passwordBtn : function() {
return this.passwordBtnInnerText;
},
passwordHintText : function() {
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
document.querySelector(".m-hint").appendChild(para);
},
addNewLabels : function(){
var selectnewPwText = document.createElement('LABEL');
selectnewPwText.innerText = "Select label Name";
selectnewPwText.classList.add("mystyle");
document.querySelector('.select-new-password').appendChild(selectnewPwText);
}
};
// Display data from the object:
document.getElementById("btn-login").innerText = resetPasswordControls.passwordBtn();
resetPasswordControls.passwordHintText();
resetPasswordControls.addNewLabels();
<form onsubmit="return false;" method="post">
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="select-new-password"></label>
<input autocomplete="off" class="form-control required" id="Password" maxlength="20" name="Password" type="password" value="" aria-required="true">
<p class="m-hint">Must use 8-20 characters and one number or symbol.</p>
</div>
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="retype-new-password"></label>
<input type="password" class="form-control" id="password" placeholder="Enter your password">
<button type="submit" id="btn-login">Some Text need to replace</button>
</div>
</form>

You can just have your function receive the attributes as an arguments, here is an example of how you can achieve that:
var resetPasswordControls = {
passwordBtnInnerText: "Something else",
passwordBtn : function() {
return this.passwordBtnInnerText;
},
passwordHintText : function() {
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
document.querySelector(".m-hint").appendChild(para);
},
addNewLabels : function(element, innerText, className, appendTo){
var selectnewPwText = document.createElement(element);
selectnewPwText.innerText = innerText;
selectnewPwText.classList.add(className);
appendTo = appendTo || 'body';
document.querySelector(appendTo).appendChild(selectnewPwText);
}
};
// Display data from the object:
document.getElementById("btn-login").innerText = resetPasswordControls.passwordBtn();
resetPasswordControls.passwordHintText();
resetPasswordControls.addNewLabels('LABEL', "Select label Name", "mystyle", '.select-new-password');
<form onsubmit="return false;" method="post">
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="select-new-password"></label>
<input autocomplete="off" class="form-control required" id="Password" maxlength="20" name="Password" type="password" value="" aria-required="true">
<p class="m-hint">Must use 8-20 characters and one number or symbol.</p>
</div>
<div class="form-group has-feedback has-feedback-left">
<label for="name" class="retype-new-password"></label>
<input type="password" class="form-control" id="password" placeholder="Enter your password">
<button type="submit" id="btn-login">Some Text need to replace</button>
</div>
</form>

Related

How to append an element to a div with className that have a child elemnt with idName

MY html has multiple divs that share the same class name and they have input elements with unique ids, I want to append a span under all of these inputs with JavaScript without editing the html.
this is the part of html
<form name="form" onsubmit="return validate();" method="get">
<div class="form-group">
<label for="pass">Password</label>
<input type="password" class="form-control" name="pass" id="pass">
</div>
<div class="form-group">
<label for="pass2">Re-Type Password</label>
<input type="password" class="form-control" name="pass2" id="pass2">
</div>
.
.
.
</form>
this my JS to create and append the span
const errorMessage = document.createElement('span');
errorMessage.textContent = "invalid input";
document.querySelector('.form-group').appendChild(errorMessage);
But this only creates one span in the first div
you should get all items has class form-group with querySelectorAll
const arrayElement = document.querySelectorAll('.form-group');
for(let i = 0; i < arrayElement.length; i++)
{
const errorMessage = document.createElement('span');
errorMessage.textContent = "invalid input";
arrayElement[i].appendChild(errorMessage);
}
more : https://jsfiddle.net/7znf685q/2/
Use querySelectorAll() and iterate.
querySelectorAll(".form-group").forEach(form => {
const errorMessage = document.createElement('span');
errorMessage.textContent = "invalid input";
form.appendChild(errorMessage);
});
querySelector just gets the first instance. You need to use querySelectorAll. Then put everything inside a loop
let group = document.querySelectorAll('.form-group')
for (let i = 0; i < group.length; i++) {
const errorMessage = document.createElement('span');
errorMessage.textContent = "invalid input";
group[i].appendChild(errorMessage);
}
<form name="form" onsubmit="return validate()" method="get">
<div class="form-group">
<label for="pass">Password</label>
<input type="password" class="form-control" name="pass" id="pass">
</div>
<div class="form-group">
<label for="pass2">Re-Type Password</label>
<input type="password" class="form-control" name="pass2" id="pass2">
</div>
</form>
You select the parent node through child id and then append you massage.
<script>
const errorMessage = 'Password Not match';
document.getElementById("pass2").parentNode.append(errorMessage);
</script>

How to make an error message for each empty form field

I am trying to display an error message for each empty field, my problem is that when I submit the form with an empty (one or two) field all the error messages appear. I want only one error message for each empty field to appear, not all of them.
HTML :
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
JavaScript:
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const password = document.getElementById("password");
if(firstName.value < 1 ) {
errorField.forEach((f) => f.classList.toggle('error-active'));
errorField.forEach((c) => c.style.color = "red");
firstName.classList.toggle("invalid");
return false;
}
if (lastName.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
lastName.classList.toggle("invalid");
return false;
}
if (email.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
email.classList.toggle("invalid");
return false;
}
if (password.value < 1) {
errorField.forEach((f) => f.classList.toggle("error-active"));
errorField.forEach((c) => (c.style.color = "red"));
password.classList.toggle("invalid");
return false;
} else {
password.classList.remove("invalid");
errorField.classList.remove("error-active");
}
return true;
}
submitButton.addEventListener('click' , validate);
Hope this fixed your issue. Notice, password changed to passwordD and you were accessing all the error field without specifying which
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
e.preventDefault();
const firstName = document.getElementById("name");
const lastName = document.getElementById("last-name");
const email = document.getElementById("email");
const passwordD = document.getElementById("password");
if (firstName.value < 1) {
errorField[0].classList.toggle('error-active');
errorField[0].style.color = "red";
firstName.classList.toggle("invalid");
}
if (lastName.value < 1) {
errorField[1].classList.toggle("error-active");
errorField[1].style.color = "red";
lastName.classList.toggle("invalid");
}
if (email.value < 1) {
errorField[2].classList.toggle("error-active");
errorField[2].style.color = "red";
email.classList.toggle("invalid");
}
if (password.value < 1) {
errorField[3].classList.add("error-active");
errorField[3].style.color = "red";
passwordD.classList.toggle("invalid");
} else {
passwordD.classList.remove("invalid");
errorField.forEach((f) => {
f.classList.remove("error-active");
f.style.color = "black";
});
return true;
}
return false;
}
submitButton.addEventListener('click', validate);
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
I would suggest you to use a form validation JS plugin instead of reinveting the wheel, for example Form Validation Plugin
You can simplify your code a bit using a class for the inputs, and keeping track of an isValid boolean for the form. You were setting all error-fields with your code. Here, we are able to reference just the error-field that applies using closest() to find the encompassing label, then querySelector to find the error-field
el.closest('label').querySelector('.error-field');
const submitButton = document.querySelector('.form-button');
const validate = (e) => {
e.preventDefault();
let isValid = true
document.querySelectorAll('.validate').forEach(el => {
let error = el.closest('label').querySelector('.error-field').classList;
if (el.value.trim().length === 0) {
isValid = false;
error.add('error-active');
el.classList.add('invalid')
} else {
error.remove('error-active');
el.classList.remove('invalid')
}
})
return isValid;
}
submitButton.addEventListener('click', validate);
.error-field.error-active,
input.invalid{
color: #f00;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" class='validate' name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" class='validate' name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" class='validate' name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" class='validate' name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>
That's because inside each if statement you are looping through all the Error fields in the form and update it all. So what you can do is first add unique id for each dom entry in the HTML file such as err-password, error-name and so on then inside each if statement grab the relevant eror field that needs to show the error and update only that field.
Using nextElementSibling would simplify your code a lot here... Since the error message always is right after the input.
In the condition to show or not the error.. That is the value.length you have to check.
const submitButton = document.querySelector('.form-button');
const errorField = document.querySelectorAll(".error-field");
const validate = (e) => {
// Remove any already displayed error
errorField.forEach(function(error){
error.classList.remove("invalid");
})
// Loop through all inputs to check the value length
document.querySelectorAll("form input").forEach(function(input){
if(input.value.length < 1){
input.nextElementSibling.classList.toggle("invalid");
}
})
// Prevent submit only if there are errors shown
let errorCount = document.querySelectorAll(".error-field.invalid").length
if(errorCount){
e.preventDefault();
}
}
submitButton.addEventListener('click' , validate);
label{
display: block;
}
label p{
margin: 0;
}
.error-field{
display: none;
color: red;
}
.invalid{
display: inline-block;
}
<form action="" id="my-form">
<label for="name">
<input type="text" id="name" name="firstName" placeholder="First Name">
<p class="error-field">First Name cannot be empty</p>
</label>
<label for="last-name">
<input type="text" id="last-name" name="lastName" placeholder="Last Name">
<p class="error-field">Last Name cannot be empty</p>
</label>
<label for="email">
<input type="email" id="email" name="email" placeholder="Email Address">
<p class="error-field">Looks like this is not an email</p>
</label>
<label for="password">
<input type="password" id="password" name="password" placeholder="Password">
<p class="error-field">Password cannot be empty</p>
</label>
<button type="submit" name="submit" class="form-button">Claim your free trial </button>
<p>By clicking the button, you are agreeing to our Terms and Services</p>
</form>

How to Identify which control is violated in parsleyjs

I want to know which control is violated...
function validate()
{
vldt = $('#frmInt').parsley().validate();
alert(" is Submitted : "+ vldt );
if(vldt == false)
{
alert(" Violdated Control is : " + ? )
}
}
A first alert box will display 'is Submitted : false',
but, how can we get why the form is violated and which control is violated...
You can listen for the field:error event or look for elements having the class parsley-error:
$('#demo-form').parsley().on('field:error', function(e) {
var attrName = this.$element.attr('name');
var lblTxt = this.$element.siblings('label[for="' + attrName + '"]').text()
console.log('Validation failed for: ', lblTxt);
});
$('#demo-form [type="submit"]').on('click', function (e) {
vldt = $('#demo-form').parsley().validate();
return vldt;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://parsleyjs.org/dist/parsley.js"></script>
<form id="demo-form" data-parsley-validate="">
<label for="fullname">Full Name * :</label>
<input type="text" class="form-control" name="fullname" id="fullname" required="">
<label for="email">Email * :</label>
<input type="email" class="form-control" name="email" data-parsley-trigger="change" id="email" required="">
<br>
<input type="submit" class="btn btn-default" value="validate">
</form>

javascript validation - Javascript not running

I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}

Failure using jquery.validate.min in ie7

I use jquery.validate.min.js version 1.9 and jquery-1.7.1.js. and i have error on validation form: SCRIPT5007: Unable to get value of the property 'form': object is null or undefined on line 102 :
valid: function() {
if ( $(this[0]).is('form')) {
return this.validate().form();
} else {
var valid = true;
var validator = $(this[0].form).validate();
this.each(function() {
valid &= validator.element(this);
});
return valid;
}
},
I was try to use jquery-1.5.2.js and standart jquery.validate.min.js but this is not work.
My code in site.js is :
$(".boxy-wrapper #genericleadform").validate({
errorElement: "",
highlight: function (element) {
$(element).addClass("notvalid");
},
unhighlight: function (element) {
$(element).removeClass("notvalid");
}
});
Generic lead form html is:
<form action="/BeautyLotery/Leads/Add" class="tot_form" id="genericleadform" method="post" name="genericleadform">
<div class="lead_wrapper">
<fieldset>
<input class="required toto_imp1" id="FirstName" name="FirstName" type="text" value="" /> <input class="required toto_imp2" id="LastName" name="LastName" type="text" value="" /> <input class="required phonenumber toto_imp3" id="Phone" name="Phone" type="text" value="" />
<input class="required emailenglish toto_imp4" id="Email" name="Email" type="text" value="" />
<label class="custom_checkbox cc1"><input type="checkbox" /><b></b></label>
<label class="custom_checkbox cc2"><input type="checkbox" /><b></b></label>
<div class="pp_msg hidden">
</div>
</fieldset> </div>
</form>
I don't understand what is problem... Can anybody help?

Categories

Resources