What I am trying to achieve is track 20 inputs, if one is filled I want to add a class to a parent div of this input, if it becomes empty after I want the class to remove itself from the parent. This code does what I want when I run it in the console, how can I improve it so it can track the inputs and toggle the class?
$('.input').each(function() {
var $input = $(this);
if ($input.val()) {
var $parent = $input.closest('.card');
$parent.addClass('colored')
}
});
You can use an event to do so. For inputs, jQuery has the input event that fires every time the value of an input changes.
$(".input").on("input", function () {
if ($(this).val().length === 0)
$(this).closest('.card').removeClass("colored");
else
$(this).closest('.card').addClass("colored");
});
Your code checks for values at the initial run. You would need to attach events copy, paste, change, keypress, keydown, keyup and input. See example:
$('input').on('copy paste keydown keyup keypress change input', function(){
var $input = $(this);
if( $input.val() == '' ){
$input.parent('.form-group').addClass('empty');
} else {
$input.parent('.form-group').removeClass('empty');
}
});
.form-group {
margin-bottom:10px;
}
.form-group.empty > input {
border:2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input name="name" type="text" placeholder="name"/>
</div>
<div class="form-group">
<input name="email" type="text" placeholder="email"/>
</div>
<div class="form-group">
<input name="address" type="text" placeholder="address"/>
</div>
This is the snippet Here. An keyup() function and an if check done them all.
$("input[type='text']").on("keyup",function(){
if($(this).val()!="")
{
$(this).parent().addClass("active");
}else{
$(this).parent().removeClass("active");
}
})
.active{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" >
</div>
Thank you all for the answers, this is what worked for me after trying all the solutions. Hope it helps someone else.
function checkInputs() {
$('.input').each(function(){
if($(this).val() === ""){
$(this).parent().parent('.unit-card').removeClass('filled');
} else {
$(this).parent().parent('.unit-card').addClass('filled');
}
});
}
Related
I trying to use form validation when a user leaves the text form.
this code is actually run as I wanted but, the problem is I cannot validate specific form I input. when I leave form name, the form number also showing an error before I have a chance to input on it.
How can I split the error message on every input into the global function when the user leaves the form text?
$(document).ready(function(){
$('input[type=text]').on('blur', function(){
$(this).each(function(){
nama ($('#nama').val());
no($('#nomor').val());
});
});
function nama(myname){
if(!myname){
$('<span>name cannot be empty</span>').insertAfter('#nama');
}
}
function no(mynomor){
if(!mynomor){
$('<span>number cannot be empty</span>').insertAfter('#nomor');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>name</p>
<input type="text" id='nama'>
<br>
<p>number</p>
<input type="text" id='nomor'>
You can simplify your code to achieve that hide show by using the error message span in the HTML itself and then selecting the span element based on the input element id. Something like this:
$(document).ready(function() {
$('input[type=text]').on('blur', function(e) {
var id = this.id;
if (e.target.value) {
$('#' + id + 'span').hide();
} else {
$('#' + id + 'span').show();
}
});
});
.error-span {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>name</p>
<input type="text" id='nama'>
<span id='namaspan' class='error-span'>name cannot be empty</span>
<br>
<p>number</p>
<input type="text" id='nomor'>
<span id='nomorspan' class='error-span'>number cannot be empty</span>
I would suggest to let the error message in the HTML, but not being displayed, then when the blur events occur, you check to see if the field is empty, if it is, then get the element with the error message and show it.
I created a function that will be called by every input[type=text] when blur occurs, that function will check/validate the field
$(document).ready(function(){
$('input[type=text]').on('blur', function(){
validateField(this)
});
function validateField(field){
let value = field.value;
if (value.trim().length < 1 || value === null){
$(field).siblings(".invalid-msg").removeClass("not-error").addClass("error-show")
}else{
$(field).siblings(".invalid-msg").removeClass("error-show").addClass("not-error")
}
}
});
.error-show{
display: inline-block;
color: red;
}
.not-error{
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>name</p>
<input type="text" id='nama'> <span class="not-error invalid-msg">Name can't be empty</span>
</div>
<br>
<div>
<p>number</p>
<input type="text" id='nomor'> <span class="not-error invalid-msg">Number can't be empty</span>
</div>
I have a form with inputs. The first input needs to be filled out before the second input.
If the user clicks on input 2 first they get a message saying to fill the other input first. Now I want to make it so that after the message pops up, if the user then fills out input one the message disappears.
My codepen.
I tried adding an onchange function but that doesn't seem to work.
$('body').on('focus', '.clickable', function() {
if (!$('.look').val().length) {
$(this).siblings('p').text('Please select Type first')
}
});
$('body').on('change', '.look', function() {
if ($('.look').val().length) {
$(this).siblings('p').text('')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
Input-1:<br>
<input type="text" name="first" id="one" class="look"><br> Input-2:
<br>
<input class="clickable" type="text" name="second" id="two">
<p class="warning"></p>
</div>
</form>
on change called when you leave the input, your code works when leaving the input, also you can change the "on change" by keyup to see the changes whitout leaving the input
codepen : https://codepen.io/anon/pen/QOzKwQ
You could use keyup as your event instead of change. Change needs to wait for you to click away from the input (blur).
$( 'body').on('focus','.clickable',function() {
if (!$('.look').val().length) {
$(this).siblings('p').text('Please select Type first')
}
});
$( 'body').on('keyup','.look',function() {
if ($('.look').val().length) {
$(this).siblings('p').text('')
}
});
Use .on("change keyup paste"...)
to detect immediate changes to the text-field
$( 'body').on('focus','.clickable',function() {
$('.look').on("change keyup paste", function(){
$(this).siblings('p').text('')
});
if (!$('.look').val().length) {
$(this).siblings('p').text('Please select Type first')
}
});
$( 'body').on('change','.look',function() {
if ($('.look').val().length) {
$(this).siblings('p').text('')
}
});
I don't mean to change your approach but you could try disabling the field so they can't click it and then enable it once input 1 has been filled?
HTML:
<form>
<div>
Input-1:<br>
<input type="text" name="first" id="one" class="look"><br>
Input-2:<br>
<input class="clickable" type="text" name="second" id="two" >
<p class="warning"></p>
</div>
</form>
The JS:
document.getElementById("two").disabled = true;
var dis1 = document.getElementById("one");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("two").disabled = false;
}
}
It will be more efficient if you track the user input using input event like :
$('body').on('input', '.look', function() {
if ($('.look').val().length) {
$(this).siblings('p').text('')
}
});
Snippet:
$('body').on('focus', '.clickable', function() {
if (!$('.look').val().length) {
$(this).siblings('p').text('Please fill the first input.')
}
});
$('body').on('input', '.look', function() {
if ($('.look').val().length) {
$(this).siblings('p').text('')
}
});
.warning {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
Input-1:<br>
<input type="text" name="first" id="one" class="look"><br> Input-2:
<br>
<input class="clickable" type="text" name="second" id="two">
<p class="warning"></p>
</div>
</form>
I have a modal with ~20 input and select fields that the user is supposed to complete. I would like to a quick JavaScript check whether the field is empty or not after the user is navigating away / changing / etc. the field, but want to avoid having to copy paste the code below 20 times and personalize it for each field.
<!-- Holidex -->
<label>Holidex:</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-bars"></i></span>
<input type="text" class="form-control" maxlength="5" placeholder="What is your Holidex code?" id="addHolidex" name="addHolidex" style="text-transform:uppercase" />
</div>
<!-- /.Holidex -->
<script type="text/javascript">
$('#addHolidex').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$('#addHolidex').removeClass('has-success').addClass('has-warning');
} else {
$('#addHolidex').addClass('has-success').removeClass('has-warning');
}
});
</script>
Is there any way to have the code above check for any select / input field on my NewUserModal?
Thank you!
EDIT
So I fiddled around with the suggested codes below but only the following managed to halfway work:
$('.input-group').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-error');
} else {
$(this).addClass('has-success').removeClass('has-error');
}
});
Empty fields are being flagged correctly now, but fields with content do not have the has-success class added. Note that I have to apply this class to the <div class="input-group"> element instead of the input select fields.
Any suggestions? I am running on bootstrap 3 if that helps.
EDIT 2
Still no result and quite frankly have had enough for today.
- select fields are either ignored or incorrectly flagged with has-error if pre-populated
- individual input fields seem to work more or less
- grouped input fields nestled in one div all turn red if one field is empty (eg. phone number + phone country both turn red of there is not country code entered)
// highlight empty fields in red
$('.input-group input, select').on('keyup keydown keypress change paste',function(){
if ($(this).val() == '') {
$(this).parent().closest('.input-group').removeClass('has-success').addClass('has-error');
} else {
$(this).parent().closest('.input-group').removeClass('has-error').addClass('has-success');
}
});
I basically would have to redo the whole design of my modal and I quite frankly dont want to go down that road. Not a fan of JS/ Jquery today.
Not really sure this is what you're looking for but, why do not simply make your code more universal:
$('input').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-warning');
} else {
$(this).addClass('has-success').removeClass('has-warning');
}
});
EDIT
If you would like to specify a precise form, add an ID to your form :
<form id="myForm">
<label>Holidex:</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-bars"></i></span>
<input type="text" class="form-control" maxlength="5" placeholder="What is your Holidex code?" id="addHolidex" name="addHolidex" style="text-transform:uppercase" />
</div>
</form>
$('#myForm input').on('keyup keydown keypress change paste', function() {
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-warning');
} else {
$(this).addClass('has-success').removeClass('has-warning');
}
});
Add a new class to the input
<input type="text" class="form-control Input-to-verify" maxlength="5" placeholder="What is your Holidex code?" id="addHolidex" name="addHolidex" style="text-transform:uppercase" />
and then in javascript:
$('.Input-to-verify').on('change',function(){
if ($(this).val() == '') {
$(this).removeClass('has-success').addClass('has-warning');
} else {
$(this).addClass('has-success').removeClass('has-warning');
}
});
I hope this works
I want my input always has value so that focus is fixed to it until the values are typed and the cursor also can't escape the input.
I know the focus() function is existed but how can i deal with it? It is just an event isn't it? Is there any solution?
This is the html code which include the input.
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
This is the script where the input is bound the events.
<script>
jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function(){
if (!$(this).val()) {
var message = "no id";
error(this.id, message); // ** TODO : SET FOCUS HERE !!
} else {
id_form_validation(this.id);
}
});
Could you guys see the **TODO in code above? I want to add function that the focus is fixed until the value is written.
Please could guys give me some idea. Thank you.
=========================================================================
I want to focus my input depends on situation. For example, I want to focus it when the value isn't existed or the validation doesn't correct. However it has to focus out when the value is existed or the validation is true.
I can set focus it finally but how can i unfocus it? I mean i want to untrigger the focus event.
jQuery('#inputID').on('blur',function(){
if (!$(this).val()) {
var message = "아이디를 입력해 주세요";
error(this.id, message);
$(this).focus();
} else {
//$(this).focus();
if (!id_form_validation(this.id)) {
$(this).focus(); // TODO : FOCUS
}else {
$(this).off('focus'); // TODO : FOCUS OUT
$(this).off('blur');
}
}
});
You can use this code to do the same... I have used blur
//jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function() {
if (!$(this).val()) {
$(this).focus();
var message = "no id";
error(this.id, message);
}else {
id_form_validation(this.id);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
Use $(this).focus() to focus your input.
focus() with no arguments will trigger that event on an element.
hello guys I have a login page with two inputs username and password and one button. I want to put a class on that button after password field has first character filled in. How can I do that , Thank's. If is possible to do that only with css will be awesome, or a small script to add a class on that button.
<form>
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last" value="login button" />
css
/*Normal State*/
.crbl{
margin-top:10px;
border:1px solid #555555;
border-radius:5px;
}
/*after password field has one character filled in state*/
.class{
???
}
fiddle:
http://jsfiddle.net/uGudk/16/
You can use toggleClass and keyup methods.
// caching the object for avoiding unnecessary DOM traversing.
var $login = $('.crbl');
$('#last').keyup(function(){
$login.toggleClass('className', this.value.length > 0);
});
http://jsfiddle.net/5eYN5/
Note that IDs must be unique.
You can do that using javascript. FIrst thing you need to put on password input the following event
Password <input type="text" name="last" id="last" onkeyup="myFunction(this);"/>
Then you define the javascript function:
function myFunction(element) {
if (element.value != '') {
document.getElementById('last').attr('class','password-1');
} else {
document.getElementById('last').attr('class','password-0');
}
}
You may try like this demo
jQuery(document).ready(function(){
jQuery('#last').keyup(function(event){
var password_length =jQuery("#last").val().length;
if(password_length >= 1){
jQuery("#last_button").addClass('someclass');
}
else
{
jQuery("#last_button").removeClass('someclass');
}
});
});
This is the best way to handle the entire input, with the "on()" Jquery method.
Use the very first parent
<form id="former">
Username <input type="text" name="first" id="first" /><br/><br/>
Password <input type="text" name="last" id="last" />
<br/>
</form>
<input class="crbl" type="submit" name="last" id="last_btn" value="login button" />
Then in Jquery
$("#former").on('keydown, keyup, keypress','#last',function(e){
var value = $(this).val();
if ( value.length > 0 ) {
$("#last_btn").addClass('class'):
}else{
$("#last_btn").removeClass('class');
}
});
With "on" method you can handle many event of the input as you can see...
make sure your ID is unique.. since you have two IDs with the same name in fiddle.. i changed the password id to 'password'...
use keyup() to check the key pressed.. and addClass() to add the class..
try this
$('#password').keyup(function(){
if($(this).val()==''){
$('#last').removeClass('newclassname'); //if empty remove the class
}else{
$('#last').addClass('newclassname'); // not not empty add
}
});
fiddle here
<script type="text/javascript">
$('#YourTextBoxId').keyup(function (e) {
if ($(this).val().length == 1) {
$(this).toggleClass("YourNewClassName");
}
else if ($(this).val().length == 0) {
$(this).toggleClass("YourOldClassName");
}
})
</script>
Test this:
http://jsfiddle.net/uGudk/33/
Please consider using unique id for all form elements, and use unique input name also.
$(document).ready(function(){
$("input[name=last]").keydown(function () {
if($(this).val().length > 0){
$(this).attr("class", "class");
//or change the submit button
$("input[type=submit]").attr("class", "class");
//or if you want to enable it if originally disbaled
$("input[type=submit]").removeAttr("disabled");
}
});
});