convert JQuery code to Pure Javascript - javascript

I'm trying to rewrite the following JQuery to Pure Javascript.
I don't know why the code isn't working, but it isn't working. I'm guessing I'm doing wrong with the use of "focusing". Would anybody help me please?
JQuery(working)
$('.form-group input').on('focus blur', function (e) {
$(this).parents('.form-group').toggleClass('active', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
This is what I have so far(not working).
const inputs = document.querySelectorAll(".form-group input")
Array.from(inputs).forEach(input => {
input.addEventListener("focusin", (e) => {
const t = e.target as HTMLInputElement
let formgroup = t.parentElement
if(t.value.length > 0 ){
formgroup.classList.toggle("onblur")
}
})
})
Here is the html tag.
<form action="#" id="login-form">
<div class="form-group">
<label class="label-control">
<span class="label-text">Email</span>
</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label class="label-control">
<span class="label-text">Password</span>
</label>
<input type="password" name="password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn" />
</form>

A couple of issues in regards to the jQuery code.
The class is named active and you are using onblur. The jquery code runs on both focus and blur.
const inputs = document.querySelectorAll(".form-group input");
const focusBlurHandler = (e) => {
const t = e.target;
let formgroup = t.parentElement;
if(t.value.length > 0 ){
formgroup.classList.toggle("active");
}
};
Array.from(inputs).forEach(input => {
input.addEventListener("focusin", focusBlurHandler);
input.addEventListener("focusout", focusBlurHandler);
});
.active{background:lightgreen}
<form action="#" id="login-form">
<div class="form-group">
<label class="label-control">
<span class="label-text">Email</span>
</label>
<input type="email" name="email" class="form-control" />
</div>
<div class="form-group">
<label class="label-control">
<span class="label-text">Password</span>
</label>
<input type="password" name="password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn" />
</form>

Related

Bootstrap form doesn't cancel submission when validation failed

I'm trying to create a form which will send an email to the user on submit.
The thing is that I used Bootstrap's form template and when I submit it with phone and mail wrong values (phone number even empty), the email is sent anyway (with 200 ok) and a success alert is showing.
Here is my HTML code:
<form class="needs-validation" novalidate id="paymentForm">
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Lasr Name</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
required Feild
</div>
</div>
</div>
<div class="mb-3">
<label for="email">Email</label>
<input type="email" class="form-control" value="" name="email" id="email" placeholder="you#example.com" required>
<div class="invalid-feedback">
please enter a valid mail address
</div>
</div>
<div class="mb-3">
<label for="phone">Phone Number</label>
<input type="tel" class="form-control" value="" name="phone" placeholder="example: 050-1111111" pattern="[0]{1}[5]{1}[0-9]{8}" id="phone" required>
<div class="invalid-feedback">
please provide a valid phone number
</div>
</div>
<div class="mb-3">
<label for="address"> address</label>
<input type="text" class="form-control" name="address" id="address" placeholder="" required>
<div class="invalid-feedback">
please provide your address
</div>
</div>
<hr class="mb-4">
<h4 class="mb-3">payment method</h4>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input id="cash" value="cash" value="cash" name="paymentMethod" type="radio" class="custom-control-input" required checked>
<label class="custom-control-label" for="cash">cash</label>
</div>
<div class="custom-control custom-radio">
<input id="bit" value="bit" value="bit" name="paymentMethod" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="bit">Bit</label>
</div>
</div>
<div class="invalid-feedback">
please choose method
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">continue to checkout</button>
</form>
and here is my js:
(function() {
'use strict'
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation')
Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
var radioValue = $('#paymentForm input:radio:checked').val()
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated')
var orderNumber = generateId();
var cName = $('#firstName').val() + " " + $('#lastName').val()
var cEmail = $('#email').val()
var cPhone = $('#phone').val()
var cAddress = $('#address').val()
var cSumToPay = parseInt(localStorage.getItem("totalPrice"));
var cProducts = JSON.parse(localStorage.getItem("products") || "[]");
cProducts = cProducts.map(Object.values);
cProducts = cProducts.join(' ');
console.log(cProducts);
var templateParams = {
order_number: orderNumber,
customer_name: cName,
products: cProducts,
addres: cAddress,
phone: cPhone,
customer: cEmail,
payment_Methode: radioValue,
customer_sum: cSumToPay
};
emailjs.send('gmail', 'orderconfirmation', templateParams)
.then(function(response) {
console.log('SUCCESS!', response.status, response.text);
alert('Yey! Your email was sent :)');
}, function(error) {
console.log('error');
alert(error);
});
event.preventDefault();
}, false)
})
}, false)
}())
I would be thankful if you guys can help me!!!
This section appears to be your only check for validation:
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
However, event.preventDefault() and event.stopPropagation() are not going to prevent the code from falling through to the next section. You can do that by including a return at this point
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
return false;
}
or you can wrap the rest of your code in the else of your conditional
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
} else {
// your email handling code
}
Note: your event.preventDefault() is useful to stop the submit button from performing its default behavior of submitting the form and event.stopPropagation() will just keep the event from bubbling up to parent elements (which you likely don't need). See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault and https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
In any case, you do not need two event.preventDefault() calls if you place a single one at the top of your event listener, e.g.
form.addEventListener('submit', function(event) {
event.preventDefault();
...

Submitting form within a function

Probably a very easy fix for you JS gurus out there, currently I have a form with some basic validation. If i call it outside of a submit function it works fine, however i need the form to submit once it checks the validation, can anyone help? Also is the correct way to call it by returning true at the bottom of the function?
function submitForm() {
//Form validation, post.
submitBtn.addEventListener("click", function(event) {
event.preventDefault();
//Form fields
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
//Check if values aren't empty, if they're not post form. Else alert the user to complete.
contactName !== '' && contactEmail !== '' && contactPhone !== '' && contactMessage !== '' ?
true :
alert("Please complete form");
})
}
<form action="#" method="post">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input id="submitbtn" type="submit" value="send my message" onsubmit="submitForm()" />
</div>
</form>
Use preventDefault() only if the validation doesn't pass.
document.getElementById('contact-form').addEventListener('submit', function(e) {
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
if (contactName === '' || contactEmail === '' || contactPhone === '' || contactMessage === '') {
e.preventDefault();
alert("Please complete form");
}
});
<form action="#" method="post" id="contact-form">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input type="submit" value="send my message" />
</div>
</form>

JavaScript Onclick is not working in tag

HTML:
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="new User().register()">REGISTER</div>
</div>
</form>
Js File
var User = function() {
var self = this;
self.register = function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/
var regEight = /^8[0-9].*$/
if($("#empId").val() =='')
{
alert(Language.InvalidEmployeeId);
return false;
}
if(mobile =='')
{
alert(Language.EmptyMobileNumber);
return false;
}
}
};
if i write a coding for click event like below its working when i use OnClick event function is not calling
$("#regBtn").click(function ()
{
new User().register();
})
how to make the onclick work.. thanks in advance
In onclick call a function that does new User().register().
Do not write literal expression, wrap that expression in function and call that function.
try with this code
$("#regBtn").click(function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/;
var regEight = /^8[0-9].*$/;
if ($("#empId").val() == '') {
// alert(Language.InvalidEmployeeId);
console.log("InvalidEmployeeId");
return false;
}
if (mobile == '') {
//alert(Language.EmptyMobileNumber);
console.log("Empty mobile number");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="javascript:if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn">REGISTER</div>
</div>
</form>
</div>
Do something like this...
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="registerUser()">REGISTER</div>
</div>
</form>
</div>
Java script
function registerUser(){
new User().register();
}
In this case the function registerUser() is re-usable as you commented above "Actually i want to make use of the onclick event so that function can be reused if i give a id i cant reuse that in another page".

React onSubmit event not working

When I hit enter on the form, it does not trigger the onSubmit event. There are no errors. The other event, onBlur, does dispatch. The logForm function will eventually console.log a JSON string of all the form's fields, but I have not yet gotten that far. I am simply trying to trigger the onSubmit event on the form. Any help or explanation would be appreciated.
Here's the code:
import React from 'react'
export default function SignupForm() {
return (
<form onSubmit={logForm}>
<div className="form-group">
<label>
Name:
<input onBlur={logUpdate} className="form-control"
type="text" placeholder="Username"/>
</label>
</div>
<div className="form-group">
<label>
Email:
<input onBlur={logUpdate} className="form-control"
type="text" placeholder="johndoe#example.com"/>
</label>
</div>
<div className="form-group">
<label>
Password:
<input onBlur={logUpdate} className="form-control"
type="password" placeholder="Password"/>
</label>
</div>
<div className="form-group">
<label>
Confirm Password:
<input onBlur={logUpdate} className="form-control"
type="password" placeholder="Password"/>
</label>
</div>
</form>
)
}
function logForm(e) {
e.preventDefault()
const formInfo = new FormData(e.target)
console.log(formInfo)
}
function logUpdate(e) {
console.log(e.target.value)
}
What you can do is put an onKeyPressed event on your form controls like so
onKeyPress={this.onKeyPressed}
and then have a function catching the onKeyPressed
onKeyPressed: function (e) {
if (e.key === "Enter") {
logForm(e);
}
}
If you want Submit to work, add a button to your html section: (Credit to #TryingToImprove)
<div className="form-group">
<label>
<button className="btn btn-default" type="submit">submit form</button>
</label>
</div>

only execute function with ng-click if input fields are not empty

I only want to perform this function if the other two fields are not empty, not sure how to do it.
ng-click="saveToList($event)"
HTML
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
Post
</div>
app.js
$scope.saveToList = function(event) {
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
if (mvName.length > 0) {
$scope.favUrls.$add({
name: mvName,
title: mvUrl
});
urlName.value = ''; //urlName is the ID of input box - Angular rocks!
urlLink.value = ''; //urlName is the ID of input box - Angular rocks!
}
}
I get this error when they are empty:
Error: $scope.mvName is undefined
The problem isn't anything to do with Angular: .trim() doesn't work against undefined values. Check to see if the variable is defined before trying to trim it, for example:
var mvName = ($scope.mvName) ? $scope.mvName.trim() : '' ;
You should initialize $scope.mvName in your controller! As it is empty, you are getting an error at line var mvName = $scope.mvName.trim();
EDIT
Post
You can add ng-disabled directive to your a tag. Something like this:
<a href ng-disabled="!mvName || !mvUrl" ng-click="saveToList($event)" class="btn btn-block post">Post</a>
or check that vars in your js:
$scope.saveToList = function(event) {
if(!$scope.mvName || !$scope.mvUrl)
return;
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
...
You could do it like this:
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
<a href="javascript:"
ng-click="(mvName != '' && mvUrl != '') && saveToList($event)" class="btn btn-block post">Post</a>
</div>
Or use ng-disabled="mvName === '' && mvUrl === ''"
Other options would be to not render the button: ng-if or ng-show.
How about performing a simple check to see if the fields are empty or not, before you perform any comparisons using the value. That should solve the issue I believe.
<form name="myForm">
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" required class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" required class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
Post
</div>
</form>
Try using the angular validation.

Categories

Resources