Validate form input on keyup with jQuery - javascript

I'm trying to build my form so that when a user fills in an input and presses enter they get the next input field.
I've got this working okay in the fact it shows the next div only I can't get the validation working...
// Form on enter next div...
$(window).load(function(){
$('footer .active input').on("keyup", function(e) {
e.preventDefault();
if (e.keyCode === 13) {
if( $('footer .active input').val().length === 0 ){
alert('NO!');
} else {
var $activeElement = $("footer .active");
$( "footer .active" ).next().addClass( "active" ).removeClass('inactive');
$activeElement.removeClass("active").addClass('inactive');
}
}
});
});
form {
overflow: hidden;
width:100%; min-height:200px;
position:relative;
}
div.inactive {
position: absolute;
display: none;
width:100%;
border-bottom:1px solid rgba(255,255,255,0.3);
}
input {
padding:2.5rem 0;
font-size:4rem;
font-weight:200;
width:80%;
}
.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer>
<form action="">
<div class="input active">
<input type="text" placeholder="Who are you?" />
</div>
<div class="input inactive">
<input type="text" placeholder="What is your Email?" />
</div>
<div class="enter-btn"></div>
</form>
</footer>

You will have to use $(document).on("keyup",'footer .active input', function(e) {})
// Form on enter next div...
$(document).on("keyup", 'footer .active input', function(e) {
if (e.keyCode == 13) {
if ($('footer .active input').val() == '') {
alert('NO!');
} else {
var $activeElement = $("footer .active");
$("footer .active").next().addClass("active");
$activeElement.removeClass("active");
}
}
});
form {
overflow: hidden;
width: 100%;
min-height: 200px;
position: relative;
}
form div.input {
position: absolute;
display: none;
width: 100%;
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
form div.input input {
padding: 2.5rem 0;
font-size: 4rem;
font-weight: 200;
width: 80%;
}
form div.input.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer>
<form action="">
<div class="input active">
<input type="text" placeholder="Who are you?" />
</div>
<div class="input">
<input type="text" placeholder="What is your Email?" />
</div>
<div class="enter-btn"></div>
</form>
</footer>

Change the line:
if( $('footer .active input').length === '' ){
to
if( $('footer .active input').val() == '' ){
and try again.
Note: you have to check the value entered in the input.
Updated Fiddle

do not use "length === '' "
length returns a interger so you can't compare it to an empty string (with typeof string)
try
if( $('footer .active input').val().length <= 0 ){

This line of code right here:
if( $('footer .active input').length === ''
This comparison is wrong for three reasons:
You're comparing an expected number value to a string value using a strict comparison operator
You should expect the value of length to be 0, not an empty string
You're comparing the property length of a jQuery object, which is equivalent to the number of DOM elements that match your selector.
Change the line to this:
if($('footer .active input').val().length == 0)
Or this, if you don't want to check the length:
if($('footer .active input').val() == '')
Note: you might want to use e.target instead of querying the same element twice.

$('footer .active input').length is the number of elements that match the selector. If you want to get the input's value use .val() instead:
// Form on enter next div...
$('footer .active input').on("keyup", function(e) {
if (e.keyCode == 13) {
if ($('footer .active input').val() == '') {
alert('NO!');
} else {
var $activeElement = $("footer .active");
$("footer .active").next().addClass("active");
$activeElement.removeClass("active");
}
}
});
https://jsfiddle.net/g51xbfy6/2/

Related

Hide a DIV and show another when I press the enter key

I'm trying to do a function that when I press the enter key it disappears a div (containerMessage) and another (containerResult) one appears, what am I doing wrong? When I press the enter key the function is not even called
A Live Example
HTML
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<img src="girlfriend.png">
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome">
</form>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
</div>
<script src="NSGM.js"></script>
</body>
</html>
Javascript
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
if (document.getElementById('containerMessage').style.display == 'block') {
document.getElementById('containerMessage').style.display = 'none'
document.getElementById('containerResult').style.display = 'block'
}
}
When you press enter, the form gets submitted, so you'll have to prevent that default behaviour:
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
e.preventDefault(); // Prevent submitting the form
validate(e);
}
});
The other issue is that you're hiding the containerMessage div which contains your containerResult, so it will never be shown. Check the snippet below, but basically you'll just have to move the containerResult div out of the containerMessage div.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
e.preventDefault();
validate(e);
}
});
function validate(e) {
let container = document.getElementById("containerMessage");
if (!container.style.display || container.style.display == "block") {
container.style.display = "none";
document.getElementById("containerResult").style.display = "block";
}
}
body {
background-color: red;
margin: 0;
}
img {
height: 50vh;
}
#bloco {
text-align: center;
margin: 0;
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
white-space: nowrap;
}
h1 {
margin: 100px 0px 0px 0px;
font-size: 10em;
}
h2 {
margin: 0;
font-size: 3em;
}
p {
font-size: 3em;
margin: 0;
}
h1,
h2,
p {
color: white;
}
input[type="text"] {
margin: 50px 0px 0px 0px;
padding: 16px 20px;
border: none;
border-radius: 8px;
background-color: #f1f1f1;
font-size: 2em;
text-align: center;
}
input[type="text"]:focus {
background-color: #ea8079;
color: white;
outline: 0;
}
#result {
font-size: 6em;
}
#containerResult {
display: none;
}
#containerMessage {
display: block;
}
<div id="bloco">
<h1>NSGM</h1>
<h2>Namorada Super Gostosa e Modelo</h2>
<div id="containerMessage">
<p id="message">Qual seu nome meu amor</p>
<form>
<input type="text" name="name" id="digitarNome" />
</form>
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
The problem is that .style.display will only return the current style if it has been previously set inline or via javascript.
Otherwise, you must use:
getComputedStyle(element, null).display
where element is previously selected in the DOM.
I removed the form from the example to remove that distraction.
var digitarNome = document.getElementById("digitarNome");
digitarNome.addEventListener("keydown", function(e) {
if (e.keyCode === 13) {
validate(e);
}
});
function validate(e) {
let msgDiv = document.getElementById('containerMessage');
let resDiv = document.getElementById('containerResult');
let divStyle = getComputedStyle(msgDiv, null).display;
if (divStyle == 'block') {
msgDiv.style.display = 'none';
resDiv.style.display = 'block';
}
}
#containerResult{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="bloco">
<div id="containerMessage">
Nome meu amor: <input type="text" name="name" id="digitarNome">
</div>
<div id="containerResult">
<p id="result">EU TE AMO RODRIGO</p>
</div>
</div>
References:
https://stackoverflow.com/a/4866269/1447509
Element.style will only retrieve the styles from the attribute on the element so
document.getElementById('containerMessage').style.display == 'block'
Will always return false
From W3 schools https://www.w3schools.com/jsref/prop_html_style.asp
Note: The style property only returns the CSS declarations set in the element's inline style attribute, e.g.
. It is not possible to use this property to get information about style rules from the section in the document or external style sheets.
You can instead apply the display style as in line attribute like so
<div id="containerMassage" style="display:block"></div>

How to check all conditions before executing aftermath

I am working on a live validation function. The problem is that the aftermath of the conditions in the function executes executes before the last part is met. The entry validation indicator should not turn green until the conditions are met, however this is not the case.
The indicator turns green after the third condition is met. It should not, until all conditions are met. Any suggestions on how I can solve this problem.
My code looks like below.
$(function() {
// Pre-define extensions
var xTension = ".com .net .edu";
$("input").keyup(function() {
// Check the position of "#" symbol
var firstLetter = $(this).val().slice(0, 1);
var lastLetter = $(this).val().slice(-1);
var userXs = "No";
// User provided extension
var userX = $(this).val();
userX = userX.substr(userX.indexOf(".") + 0);
if (xTension.indexOf(userX) > -1) {
if (userX != "") {
userXs = "Yes";
} else {
userXs = "No";
}
} else {
userXs = "No";
};
if ($(this).val().indexOf("#") > -1 && (firstLetter != "#") && (lastLetter != "#") && (userXs != "No")) {
$("#input-status").removeClass("red").addClass("green");
} else {
$("#input-status").removeClass("green").addClass("red");
}
});
});
.rack {
width: 250px;
margin: 0 auto;
}
#input-status {
width: 1px;
height: 3px;
with: 0;
display: inline-block;
transition: all 2s;
}
input {
width: 230px;
height: 30px;
text-align: center;
}
#input-status.green,
#input-status.red {
width: 235px;
background: darkGreen;
transition: all 2s;
}
#input-status.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rack">
<h1>Live Validat.ion</h1>
<input type="text" placeholder="Enter email address">
<div id="input-status">
</div>
</div>
Make xTension an array, not a string. If the user types user#foo.c, userX will be .c and this will be matched by indexOf() with the string, since there's nothing that forces it to match whole words. When you do this, you no longer need to check whether userX is an empty string.
I've made a few other simplifications to the code:
Instead of getting the first and last characters, just test the position of # against appropriate limits.
No need for + 0 after indexOf().
Don't keep calling $(this).val(), put it in a variable.
User a boolean variable for userXs.
$(function() {
// Pre-define extensions
var xTension = [".com", ".net", ".edu"];
$("input").keyup(function() {
var val = $(this).val();
// User provided extension
userX = val.substr(val.indexOf("."));
userXs = xTension.indexOf(userX) > -1;
atPos = val.indexOf("#");
if (atPos > 0 && atPos < val.length - 1 && userXs) {
$("#input-status").removeClass("red").addClass("green");
} else {
$("#input-status").removeClass("green").addClass("red");
}
});
});
.rack {
width: 250px;
margin: 0 auto;
}
#input-status {
width: 1px;
height: 3px;
with: 0;
display: inline-block;
transition: all 2s;
}
input {
width: 230px;
height: 30px;
text-align: center;
}
#input-status.green,
#input-status.red {
width: 235px;
background: darkGreen;
transition: all 2s;
}
#input-status.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rack">
<h1>Live Validat.ion</h1>
<input type="text" placeholder="Enter email address">
<div id="input-status">
</div>
</div>

How to change the background color of an input field when text is entered?

I'm pretty new with Javascript and jQuery, and can't seem to indentify the reason why my code acts like it does.
I have created two seemingly identical functions to change the background color of an input field.
Their goal is to turn the background color of the given input field to the color #00FF7F if anything is typed in the field. And if not, the field should be transparent.
Code JS:
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
css:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
Simple HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<!-- Stylesheet link -->
<link rel="stylesheet" type="text/css" href="assets/style.css">
<!-- jQuery link -->
<script type="text/javascript" src="assets/vendor/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<!-- Javascript link-->
<script type="text/javascript" src="assets/js/javascript.js"></script>
</body>
On the jsbin above, try typing in both the Username and Password field to see how they react differently.
Images of what happens. Didn't want to include all images here:
http://imgur.com/a/qgubP
I realize there probably is a way to compromise my js/jquery into 1 function that each input field calls instead of have a function for each.
If both of these fields are required, here's a much simpler solution using CSS only.
Add the attribute required to your <input> tags and then use the pseudo-class :valid.
.form-control:valid {
background-color: #00FF7F;
}
Code snippet:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
.form-control:valid {
background-color: #00FF7F;
}
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username" required>
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
jsFiddle : https://jsfiddle.net/7vzjz2u5/3/
jQuery
$(document).ready(function() {
$('.change-background').on('change', function() {
var $this = $(this);
var value = $.trim($this.val());
// toggleClass can be provided a bool value,
// If we provide true we add class, if false we remove class
$this.toggleClass('filled-background', value.length !== 0);
}).change();
// We also want to call a 'change' event on
// all inputs with the change-background class just incase the page has
// pre-filled in values
});
Instead of listening for the keyup event and then running a function, just create a listener on the change event, also if we just apply one class to all inputs we want the background colour to change on, we can just create one listener which will do it for any input with the class change-background.
Html
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="change-background form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="change-background form-control" placeholder="Password">
</div>
</div>
Css (the extra class for background color)
.filled-background {
background-color: #00FF7F;
}
Also side note
listening for keyup is back, someone may want to copy and paste their username and password and if they do this it won't trigger an keyup event if they use right click and paste.
Your code clears the background color when the length is 0. The way it checks the length is with this snippet of code:
var value = $.trim($(".form-control").val());
The selector $(".form-control") will select all elements with the CSS class of .form-control. This is a problem because there is more than one of them; in this case, it will always return the value from the first element found.
You should change the code to check for the specific control by searching by ID, like so:
var value = $.trim($("#logindata1 input").val()); //get user ID
var value = $.trim($("#logindata2 input").val()); //get password
You have some minor mistakes, but no worry. We can fix it.
First Problem
Other answers are pointing something important: you are trying to get the value selecting all elements with form-control class.
var value = $.trim($(".form-control").val());
You can do it, replacing your selector by your already declared variables $input1 and $input2. This way:
var value = $.trim($input1.val());
var value = $.trim($input2.val());
Second
Ok. First problem solved. The second problem is in your second function. You trying to set an invalid css: $input2.css("#background-color", "transparent");
When should be: $input2.css("background-color", "transparent"); (without #).
Next One
Nice. Next one. The id's you are setting logindata1 and logindata2 are on your divs. So, you are wrongly trying to get the value of the div instead the value of the input. you can fix your selector by appending input, this way:
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
Finally
So, finally, it should work:
$(document).ready(function () {
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
function onChangeInput1() {
$input1.css("background-color", "#00007F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00007F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
Your value check is not right. With your jQuery, you are checking the value of both inputs every time.
Try checking the single inputs that you are interested in instead.
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});

Contenteditable div with max length and jquery

There is the following task - I need to prevent input more than N symbols in contenteditable div with native JS / JQuery, i.e. user inputs 10 symbols and can't input more, only clear.
<div contenteditable="true" placeholder="Текст сообщения" class="editable ng-valid ng-valid-maxlength ng-dirty ng-valid-parse ng-touched"></div>
This should work for you The fiddle is here
$('#editcontent').on('keydown', function(event) {
$('span').text('Characters entered:' + $(this).text().length);
if ($(this).text().length === 10 && event.keyCode != 8) /*delete*/ {
event.preventDefault();
}
});
body {
padding: 10px 0 0 10px;
}
#editcontent {
width: 200px;
height: 50px;
border: 1px solid blue;
}
#editcontent:after {
color: #999;
content: 'Enter text';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editcontent" contenteditable="true"></div>
<span></span>

show hide no of divs according to the current index jquery

I am working with jQuery index. Here I need to add and remove divs according to the current index.
What I looking for is I need to remove first four divs when my current index is greater than 7 and I need to show those removed first four divs again when my current index is less than four(4).
I used :lt(4) to hide first four divs. But I have no idea how to get it back to show.
Thanks in Advance
$(window).load(function() {
$(document).keydown(function(e) {
if (e.keyCode == 37){
}
else if (e.keyCode == 39){
}
else if (e.keyCode == 40){
var cIndex = $('.foo.active').index();
if(cIndex > 7) {
$('.test').find('.foo:lt(4)').remove();
}
}
else if (e.keyCode == 38){
var cIndex = $('.foo.active').index();
if(cIndex < 4) {
$('.test').find('.foo:lt(4)').add();
}
}
});
});
.test {
width: 420px;
height: 200px;
text-align: center;
}
.foo {
width: 100px;
height: 100px;
line-height: 100px;
display: inline-block;
background: #ccc;
margin-bottom: 4px;
}
.foo.active {
background: #565656;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<div class="foo active">1</div>
<div class="foo">2</div>
<div class="foo">3</div>
<div class="foo">4</div>
<div class="foo">5</div>
<div class="foo">6</div>
<div class="foo">7</div>
<div class="foo">8</div>
<div class="foo">9</div>
<div class="foo">10</div>
<div class="foo">11</div>
<div class="foo">12</div>
</div>
You can add class hide to those element you gonna hide, then when you want show them back use that class and select them, just like this:
$('.foo:lt(4)').addClass('hide').fadeOut();
// when you show them back
$('.foo.hide').removeClass('hide').fadeIn();

Categories