jquery validation on blur on all input text - javascript

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>

Related

JQuery input messages

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>

Track inputs and toggle class with jQuery

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');
}
});
}

Adding exceptions in blur event

I'm making a simple Multiple Choice Question form. I want to put validation that if a user clicks on Question <textarea> and clicks somewhere else on page while not entering value in <input type="text" name="q1_option1"> of options of the question, then the user should get an alert("Wait, you forgot to enter options for Question 1");. I tried doing it like this but it's simply not the thing that i want. Here is the <html>
<div class="right">
<div class="row" style="margin:5px;">
<label><strong>Question 1</strong></label>
<div>
<textarea name="question1"></textarea>
</div>
</div>
<div class="row">
<div class="span-4"><input type="text" name="q1_option1" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option2" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option3" value="" class="q1" /></div>
<div class="span-4"><input type="text" name="q1_option4" value="" class="q1" /></div>
<div class="clear"></div>
</div>
</div>
And this is <script>
<script type="text/javascript">
$(function(){
$('textarea[name=question1]').blur(function(){
$('.right').click(function(event) {
if($(event.target).is('input[name=q1_option1]')) {
$('#alert_error_message').text('Please enter all options in Question 1!!');
callalert();
return false;
}
else
{
alert('Not working!');
}
})
})
})
</script>
Now what is happening in this code, when the user clicks on <input> to enter the options, blur is fired and user gets the alert.
What i want that if a user clicks on these <input> of answers, he should not get the alert, else, the user must get the alert for not entering values in the <input> of options!!
DEMO
I came up with below approach and I will explain what I am doing with the below code. Check for the inline comments.
$(function(){
var hasFocus=false; //this variable is used to check whether focus was on textarea
//when clicked on document
$('textarea[name=question1]').blur(function(event){
setTimeout(function(){
hasFocus=false; //on blur set the variable to false but after sometime
},100);
}).focus(function(){
hasFocus=true; //on focus set it to true again
});
//A click event on document so that to display alert only if textarea had focus and the
//targetted element is not radio button
$(document).on('click',function(e){
if($(e.target).attr('class')!='q1' && hasFocus && $(e.target).attr('name')!="question1")
{
if(!$('.q1:checked').length) //if any radio has been checked
{
//if not checked then display alert
alert('Please select an option');
}
}
});
})
How about this?
var all_filled = true;
// for each component having class "q1", if the value is empty, then all_filled is false
$('.q1').each(function(comp){
if(comp.val() == ''){
all_filled = false;
break;
}
});
// if not all input is filled, then do what you want
if(!all_filled){
// do what you want
}

Printing text next to a form field in JavaScript

I'm having a bit of trouble with this assigment and would like your help.
We are meant to create a product registration form page with all the regular expressions and everything and display the correct error when the regexes don't match.
I am trying to print a tick or say OK next to a form field but I can't get the right function. My form right now looks like this: http://www.imageurlhost.com/images/98zrdmrmsvbxnwowrvsf.png
The "Please enter product ...." is activated by jquery with a slideUp and slideDown function with onblur on the text field.
So I want to display OK where the red circle is after you click away from it, and then if you change it to something that doesn't match the OK disappears and my alert shows up. So this is my code so far:
My html form:
<div>
<input type="text" class="name" placeholder="Name" name="name" onblur="return validateProductName()"> <p class ="p11" id="p1"></p>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
My css:
.p11 {
float: right;}
My jQuery:
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
And then my JavaScript:
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
So, it prints the OK in between the field on the right side, but I want it right next to the field like I showed in the picture and I can't get this to work! I want it to disappear if I go back to the form and put something wrong...
Thanks guys!
I assume, you have no problem with the jQuery itself, you have a problem of showing it next to input box. So,
Create a <span id='tick'> tag after the input field
And once it passes the validation, use jquery to show the tick
$('#tick').html('whatever you want');
EDIT: You dont have to include the float:left on span
Check out the fiddle link
EDIT:
In this validation function, just show and hide according to the validation results
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
document.getElementById("tick").style.display = 'none'; // to hide the OK text if enterd the wrong input
} else {
document.getElementById("tick").innerHTML = "OK"; //NOTE: This is for showing the ok text
document.getElementById("tick").style.display= "block";
}
}
Create a span wherever you want your tick to be displayed and they do this,
$("#btn").click(function() {
if ($("#txtname").val() == "") //can be any check
{
$("#g").attr("style", "display:block;width:20px");
} else {
$("#g").attr("style", "display:none;width:20px;");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="txtname" style="display:inline-block" placeholder="enter name" />
<img id="g" style="width:50px;display:none;" src="http://pixabay.com/static/uploads/photo/2014/04/02/10/19/check-303494_640.png" />
<br/>
<input type="button" id="btn" value="click to submit" />
This should work-
<script src="jq.js"></script>
<div>
<input type="text" class="name" placeholder="Name" name="name" id="input"> <span class ="p11" id="p1"></span>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
<style>
p11 {
float: right;}
</style>
<script>
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
validateProductName()
});
</script>
<script>
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.getElementById("input").value.trim() == "" || document.getElementById("input").value.length > 50 ) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
document.getElementById("p1").innerHTML = "";
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
</script>

Remove input text when click button

I'm trying to remove input's val when clicking a button that appear when focusing on input.
This is my html:
<div class="search-area">
<form action="#" id="ingredientSearchForm">
<input type="text" placeholder="Arama" id="ingredientsSearch"/>
<span class="clearable"></span>
<span></span>
<input id="ingredientSearchSubmit" type="submit" class="hidden" placeholder="Arama"/>
</form>
</div>
And this is javascript function:
var searchinput = $(".search-area").find("input");
searchinput.focus(function(){
$(this).data('placeholder',$(this).attr('placeholder'));
$(this).attr('placeholder','');
$(this).siblings(".clearable").show();
});
$(".search-area").find(".clearable").on("click", function() {
$(this).val('');
});
searchinput.blur(function(){
$(this).attr('placeholder',$(this).data('placeholder'));
$(this).siblings(".clearable").hide();
});
.clearable is a span with background. Normally it is display:none.
I think you're wanting to clear searchinput on clicking .clearable?
If so, you should instead use:
$(".search-area").find(".clearable").on("click", function() {
searchinput.val('');
});
if you want to remove value of span then:
$(".search-area").find(".clearable").on("click", function() {
$(this).text('');
});
if you are trying to remove textbox value then:
$(".search-area").on("click",".clearable", function() {
$(this).closest("#ingredientSearchForm").find('#ingredientsSearch').val('');
});

Categories