JQuery addClass working in a very odd manner - javascript

I have a form with 3 inputs: 2 text inputs for a Username and E-mail and a third password input for, you guessed it, a password.
I'm validating these input fields in JQuery and when an input is either empty or doesn't match it's format, it adds a class to the input with a red border. The code goes as follows:
if ($("input#username").val().length < 6) {
$("input#username").addClass('input-error');
next_step = false;
} else if (!isEmail($("#email").val())) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword($("#pwd").val())) {
$("#pwd").addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
next_step = true;
}
It works perfectly with both Username and E-mail fields, and it also works if the Password field is empty, but even though it validates perfectly, the addClass() doesn't work if the Password doesn't meet it's requirements (At least one Uppercase letter and one number).
This is what the browser console shows:
As you can see, it kind of adds the class, but then not really.
What is happening? If you need the HTML code and/or the CSS code, tell me!
Thanks for your attention!
EDIT
Here is the HTML and CSS as requested:
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>
and the CSS:
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}

This is working for me.
Please comment what is still not working if you have this kind of setup?
function isEmail(email) { // dummy example
return email.indexOf("#")>1;
}
function isPassword(passwd) { // dummy example
return passwd.indexOf("x")>=0; // must contain x
}
$(function() {
$(".btn-next").on("click", function() {
$(".form-group input").removeClass('input-error');
var next_step = true,
user = $("#username").val(),
email = $("#email").val(),
pwd=$("#pwd").val();
if (user.length < 6) {
$("#username").addClass('input-error');
next_step = false;
} else if (!isEmail(email)) {
$("#email").addClass('input-error');
next_step = false;
} else if (!isPassword(pwd)) {
$("#pwd").addClass('input-error');
next_step = false;
}
console.log(next_step);
});
});
.form-control {
height: 40px;
border: 2px solid black;
border-radius: 0;
font-size: 14px;
}
.form-control:focus {
border: 2px solid black;
box-shadow: 0;
}
.input-error {
border-color: #FF2859;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<fieldset>
<div class="form-bottom">
<img src="img/gbsnlogo.svg" alt="GBSN Research" name="GBSN Research" width="50%" class="signupLogo" />
<br>
<br>
<br>
<div class="form-group">
<label for="username"><h1>USERNAME:</h1></label>
<input type="text" class="form-control" id="username" placeholder="Enter username..." name="username">
</div>
<div class="form-group">
<label for="email"><h1>E-MAIL:</h1></label>
<input type="text" class="form-control" id="email" placeholder="Enter e-mail..." name="email">
</div>
<div class="form-group">
<label for="pwd"><h1>PASSWORD:</h1></label>
<input type="text" class="form-control" id="pwd" placeholder="Enter password..." name="pwd">
</div>
<div class="text-center">
<button type="button" class="btn-next btn-nav"><h1>NEXT</h1></button>
</div>
</div>
</fieldset>

From what I see from the image you posted
I can only speculate this is what happened.
The line [input#pwd.form-control.input-error] was evaluated immediately when it got printed to the console. So that mean at that time, the dom does have the class input error in it. However, when you expand it, the dom got re-evaluated again. And at that time, the dom's class input-error got removed, so you don't see it anymore. I was able to prove this by running $('#pwd').addClass('input-error') and $('#pwd').removeClass('input-error') in that order, image below
Based on that, I suspect you have another logic in the code that remove the class shortly after you have added the class to the dom, highly possibly $(this).removeClass('input-error');.

Related

How do I make my javascript code for adding a new class to HTML more responsive?

<div class="control">
<input
type="email"
id="email"
class="email-address"
onblur="getValEmail()"
/>
<label for="email">Email</label>
</div>
<div class="control box">
<textarea id="message" onblur="getValMsg()"></textarea>
<label for="message">message</label>
</div>
function getValEmail() {
const valEmail = document.getElementById("email");
valEmail.addEventListener("blur", function () {
if (valEmail.value) valEmail.parentElement.classList.add("filled");
else valEmail.parentElement.classList.remove("filled");
});
}
function getValMsg() {
const valMsg = document.getElementById("message");
valMsg.addEventListener("blur", function () {
if (valMsg.value) valMsg.parentElement.classList.add("filled");
else valMsg.parentElement.classList.remove("filled");
});
}
.filled label,
input:focus + label,
textarea:focus + label {
top: 0;
font-size: 1.2rem;
}
These are HTML, Javascript and CSS codes in order.
What I'm trying to achieve here is that once user writes email address/message, labels that are inside of input/textarea go up. So, when input/textarea are filled up, labels should disappear to the top. It does its job but not responsively. "filled" class is added after a couple of more clicks happen, which means that labels only go up to the top after I click the box again.
Result looks like this.
This is only achieved after a few more clicks in the box.
You don't need js here at all. The :placeholder-shown pseudo-class will do what you actually need to achieve (note the non-empty placeholder attrs required for chrome):
.control {
position: relative;
margin-top: 20px;
}
input+label,
textarea+label {
position: absolute;
left: 0;
top: 0;
transition: 300ms;
}
input:focus+label,
input:not(:placeholder-shown)+label,
textarea:focus+label,
textarea:not(:placeholder-shown)+label {
top: -20px;
}
<div class="control">
<input type="email" id="email" class="email-address" placeholder=" " />
<label for="email">Email</label>
</div>
<div class="control box">
<textarea id="message" placeholder=" "></textarea>
<label for="message">message</label>
</div>
Here's a codepen.
In your css use:
transform:translateY(-2em)
change accordingly to your adjustment.

Why I can't add another class inside my element with bootstrap class form-control? if I add but it does not work

When I try to insert class using element.classList.add("anyClass"); it does not work, if it had form-control bootstrap class as I have given inside code, if I use remove instead of add and type element.classList.remove("form-control"); it works fine
function validation() {
var first_name = document.getElementById("first_name");
// var last_name=document.getElementById("last_name");
// var address=document.getElementById("address");
// var phone_no=document.getElementById("phone_no");
// var email=document.getElementById("email");
if (first_name.value === "") {
first_name.classList.add("add_border_left");
first_name.focus();
return false;
}
return true;
}
.add_border_left {
border-left: #d9534f 4px solid;
}
<div class="row">
<label for="">First Name</label>
<input class="form-control" onkeydown="clear_first_name();" autocomplete="off" type="text" id="first_name" autofocus>
<!-- <label id="valid_first_name" for="">Please Enter Valid First Name</label> -->
</div>
<div class="row">
<button type="submit" style=" margin-top: 30px; letter-spacing: 2px;" class="btn btn-outline-info btn-block">Submit</button>
</div>
Would you please also mention clear_first_name() method.
For now, I just place validation() method on replacing of that and class is added.
function validation()
{
var first_name=document.getElementById("first_name");
// var last_name=document.getElementById("last_name");
// var address=document.getElementById("address");
// var phone_no=document.getElementById("phone_no");
// var email=document.getElementById("email");
console.log(first_name.value)
if(first_name.value === "")
{
first_name.classList.add("add_border_left");
first_name.focus();
return false;
}
return true;
}
.add_border_left
{
border-left: #d9534f 4px solid;
}
<div class="row">
<label for="">First Name</label>
<input class="form-control" onkeydown="validation();" autocomplete="off" type="text"
id="first_name" autofocus>
<!-- <label id="valid_first_name" for="">Please Enter Valid First Name</label> -->
</div>
<div class="row">
<button type="submit" style=" margin-top: 30px; letter-spacing: 2px;"
class="btn btn-outline-info btn-block">Submit</button>
</div>

One HTML form text box doesn't show keyboard input in Firefox

I have a form in my HTML that takes in first name, last name, and phone number to create an account ID. The input textboxes for first name, last name, and account ID accept keyboard input and display it, as would be expected. However, when I'm viewing the page on the Firefox browser, only the phone number textbox doesn't work. I can click into the box once and see the cursor, but as soon as I start typing, no text shows up, and the cursor disappears. However, based on the Javascript creating an account ID with the last four digits of the phone number typed, I know the input is recognized. It works in other browsers, just not in Firefox.
<article>
<h2>New Account Information</h2>
<form>
<fieldset id="deliveryinfo">
<label for="fnameinputacct">First Name</label>
<input type="text" id="fnameinputacct" name="fname" />
<label for="lnameinputacct">Last Name</label>
<input type="text" id="lnameinputacct" name="lname" />
<label for="phoneinputacct">Phone Number</label>
<input type="text" id="phoneinputacct" name="phone" />
<label for="accountidbox">Account ID</label>
<input type="text" id="accountidbox" name="accountid" />
</fieldset>
<fieldset id="submitbutton">
<input type="submit" id="submitBtn" value="Create Account" />
</fieldset>
</form>
</article>
Here is the CSS
fieldset {
margin-bottom: 10px;
position: relative;
padding: 2.5em 1em 0.5em 1em;
background: #e3d5ba;
}
#deliveryinfo label {
display: block;
float: left;
clear: left;
margin-top: 5px;
}
#deliveryinfo input {
display: block;
margin-left: 130px;
}
#fnameinputacct, #lnameinputacct, #phoneinputacct, #accountidbox {
width: 12em;
}
#submitBtn {
font-size: 1.25em;
}
And some Javascript that goes with the fields. This method is added in another function.
function createID() {
var fname = document.getElementById("fnameinputacct");
var lname = document.getElementById("lnameinputacct");
var phone = document.getElementById("phoneinputacct");
var account = document.getElementById("accountidbox");
var fields = document.getElementsByTagName("input");
var acctid;
var fistInit;
var lastInit;
if (fname != "" && lname != "" && phone != "") {
fistInit = fname.value.charAt(0).toUpperCase();
lastInit = lname.value.charAt(0).toUpperCase();
acctid = fistInit + lastInit + phone.value.substring(phone.value.length - 4);
account.value = acctid;
newAccountArray = [];
for (var i = 0; i < fields.length - 1; i++) {
newAccountArray.push(fields[i].value);
}
}
}
You might try breaking up your form field groups with a <div> or <p>.
See https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/How_to_structure_an_HTML_form
Some of the widely used css frameworks do this as well. Look at Semantic UI, Bootstrap, or Material. These do a similar grouping with div containers for each label/input
Example from semantic ui form:
<form class="ui form">
<div class="field">
<label>First Name</label>
<input type="text" name="first-name" placeholder="First Name">
</div>
<div class="field">
<label>Last Name</label>
<input type="text" name="last-name" placeholder="Last Name">
</div>
<div class="field">
<div class="ui checkbox">
<input type="checkbox" tabindex="0" class="hidden">
<label>I agree to the Terms and Conditions</label>
</div>
</div>
<button class="ui button" type="submit">Submit</button>
</form>

JQuery won't change HTML of an id

So I have a form and a script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="contact">
<label for="prenom">Prénom</label>
<input type="text" id="prenom" name="prenom" placeholder="Votre prénom.." class="champ">
<label for="nom">Nom</label>
<input type="text" id="nom" name="nom" placeholder="Votre nom.." class="champ"><br/>
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Votre nom.." class="champ"><br/>
<label for="country">Pays</label>
<select name="country" id="country" class="champ">
<option value="france">France</option>
<option value="Canada">Canada</option>
<option value="Suisse">Suisse</option>
<option value="Belgique">Belgique</option>
</select><br/>
<label for="sujet">Sujet : </label>
<textarea class="champ" name="sujet" id="sujet" placeholder="Exprimez-vous.." style="height:200px; width=600px;"></textarea ><br/>
<input type="submit" value="Envoyer" class="champ" id="envoi">
</form>
<div id="errorMessage"></div>
<script type="text/javascript">
var errorMessage="";
$("#envoi").click(function () {
if($("#prenom").val()==""){
errorMessage+="<p>Remplissez votre prénom!</p>";
}
if($("#nom").val()==""){
errorMessage+="<p>Remplissez votre nom!</p>";
}
if($("#email").val()==""){
errorMessage+="<p>Remplissez votre email!</p>";
}
if($("#pays").val()==""){
errorMessage+="<p>Sélectionnez votre pays!</p>";
}
if($("#sujet").val()==""){
errorMessage+="<p>Remplissez votre message!</p>";
}
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
});
</script>
I have a problem with this :
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
I wish it would display the error message in
right before the script. The program does get into the if condition, because the alert appears. However, it does not display the error.
What am I doing wrong please?
Thanks,
It's due to your page is being reloaded after being submitted.
If you want to display an error (validation) you should return false.
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
return false;
}
simply just add the following in your code to Acheive your goal
e.preventDefault();
Here is the working jsfiddle:https://jsfiddle.net/1b5pcqpL/
The button trigger you are using is of type=submit which is causing your form to submit.
Instead try using type=button and submit the form after jquery validation.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="contact">
<label for="prenom">Prénom</label>
<input type="text" id="prenom" name="prenom" placeholder="Votre prénom.." class="champ">
<label for="nom">Nom</label>
<input type="text" id="nom" name="nom" placeholder="Votre nom.." class="champ"><br/>
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Votre nom.." class="champ"><br/>
<label for="country">Pays</label>
<select name="country" id="country" class="champ">
<option value="france">France</option>
<option value="Canada">Canada</option>
<option value="Suisse">Suisse</option>
<option value="Belgique">Belgique</option>
</select><br/>
<label for="sujet">Sujet : </label>
<textarea class="champ" name="sujet" id="sujet" placeholder="Exprimez-vous.." style="height:200px; width=600px;"></textarea ><br/>
<input type="button" value="Envoyer" class="champ" id="envoi">
</form>
<div id="errorMessage"></div>
<script type="text/javascript">
$("#envoi").click(function () {
var errorMessage="";
if($("#prenom").val()==""){
errorMessage+="<p>Remplissez votre prénom!</p>";
}
if($("#nom").val()==""){
errorMessage+="<p>Remplissez votre nom!</p>";
}
if($("#email").val()==""){
errorMessage+="<p>Remplissez votre email!</p>";
}
if($("#pays").val()==""){
errorMessage+="<p>Sélectionnez votre pays!</p>";
}
if($("#sujet").val()==""){
errorMessage+="<p>Remplissez votre message!</p>";
}
if(errorMessage!=""){
alert("hey");
$("#errorMessage").html(errorMessage);
}
else{
$("#contact").submit();
}
});
</script>
The message is appended to the DOM, what happens is that the form get submitted and that causing the page to reload (happens so fast you can't notice it). You'll have to prevent the default behavior of the event (which is submitting the form right after the alert and the message is appended to the DOM)!
Note: Change your click event to the submit event to prevent the user from submitting via enter key as well.
<script type="text/javascript">
$("#contact").submit(function (event) { // listen to the submit event on the form #contact itself (event is needed so we can prevent its default behavior)
var errorMessage = ""; // this should be here
// ...
if(errorMessage != ""){
alert("hey");
$("#errorMessage").html(errorMessage);
event.preventDefault(); // stop the submit (we encountered an error so mission abort :D)
}
});
</script>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.min.js"></script>
<style type="text/css">
body {
font-family: helvetica, sans-serif;
font-size:130%;
}
input {
padding: 5px 5px 12px 5px;
font-size: 25px;
border-radius: 5px;
border: 1px solid grey;
width:320px;
}
label {
position: relative;
top:12px;
width:200px;
float: left;
}
#wrapper {
width: 550px;
margin: 0 auto;
}
.form-element {
margin-bottom: 10px;
}
#submitButton {
width: 130px;
margin-left: 200px;
}
#errorMessage {
color: red;
font-size: 90% !important;
}
#successMessage {
color: green;
font-size: 90% !important;
display:none;
margin-bottom:20px;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="successMessage">You've done it! Congratulations.</div>
<div id="errorMessage"></div>
<div class="form-element">
<label for="email">Email</label>
<input type="text" name="email" id="email" placeholder = "eg. yourname#gmail.com">
</div>
<div class="form-element">
<label for="phone">Telephone</label>
<input type="text" name="phone" id="phone" placeholder = "eg. 0123456789">
</div>
<div class="form-element">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<div class="form-element">
<label for="passwordConfirm">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm">
</div>
<div class="form-element">
<input type="submit" id="submitButton" value="Sign Up"
</div>
</div>
<script type="text/javascript">
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#submitButton").click(function() {
var errorMessage = "";
var fieldsMissing = "";
if ($("#email").val() == "") {
fieldsMissing += "<br>Email";
}
if ($("#phone").val() == "") {
fieldsMissing += "<br>Telephone";
}
if ($("#password").val() == "") {
fieldsMissing += "<br>Password";
}
if ($("#passwordConfirm").val() == "") {
fieldsMissing += "<br>Confirm Password";
}
if (fieldsMissing != "") {
errorMessage += "<p>The following field(s) are missing:" + fieldsMissing;
}
if (isEmail($("#email").val()) == false) {
errorMessage += "<p>Your email address is not valid</p>";
}
if ($.isNumeric($("#phone").val()) == false) {
errorMessage += "<p>Your phone number is not numeric</p>"
}
if ($("#password").val() != $("#passwordConfirm").val()) {
errorMessage += "<p>Your passwords don't match</p>";
}
if (errorMessage != "") {
$("#errorMessage").html(errorMessage);
} else {
$("#successMessage").show();
$("#errorMessage").hide();
}
});
</script>
</body>
How come it works in this case?

Hidden div isn't showing on focus

I am trying to do a simple registration with javascript cheking stuff on the same site. I have a problem with a hidden DIV that's supposed to show when the user clicks on password input, it doesn't show. http://jsfiddle.net/mohamedyousef1980/wy2Lkscp/
This is the javascript part
$('input[type=password]').keyup(function() {
var pswd = $(this).val();
//pass lenght
if ( pswd.length < 8 ) {
$('#length').removeClass('valid').addClass('invalid');
} else {
$('#length').removeClass('invalid').addClass('valid');
}
//capital letter
if ( pswd.match(/[A-Z]/) ) {
$('#capital').removeClass('invalid').addClass('valid');
} else {
$('#capital').removeClass('valid').addClass('invalid');
}
//number
if ( pswd.match(/\d/) ) {
$('#number').removeClass('invalid').addClass('valid');
} else {
$('#number').removeClass('valid').addClass('invalid');
}
}).focus(function() {
$('#pswd_info').show();
}).blur(function() {
$('#pswd_info').hide();
});
And the html :
<form class="form" action="http://google.com" method="post">
<label name="nick">Nick:</label>
<input type="text" id="username" name="username"/> <br>
<label name="email">Email:</label>
<input type="text" id="email"/> <br>
<label name="pass">Heslo:</label>
<input type="password" id="pswd" name="pswd" />
<div id="pswd_info">
<h4>Password must meet the following requirements:</h4>
<ul>
<li id="capital" class="invalid">At least <strong>one capital letter</strong></li>
<li id="number" class="invalid">At least <strong>one number</strong></li>
<li id="length" class="invalid">Be at least <strong>8 characters</strong></li>
</ul>
</div> <br>
And the pswd class :
#pswd_info {
width:220px;
padding:5px;
background:#fefefe;
font-size:.875em;
border-radius:20px;
box-shadow:0 1px 3px #ccc;
border:1px solid #ddd;
display:none;
}
And in the head :
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="script.js"></script>
Your code works. Please check your input selector or input name at the end input exist.
Or just add below appropriate section of your page:
<input type="password" name="yourname">
There was a differnet problem, a mistake on my side.
The $(document).ready(function() { didnt cover the whole script. Sorry for wasting your time.

Categories

Resources