Showing error message using jQuery and making it disappear - javascript

Below is a simple jQuery code for showing error messages on submission of form, if the given conditions are not fulfilled. This works fine and shows error messages on form submission but I want to change it to keyup function which seems easy, changing $('#submit').click(function() { to $("input").keyup(function(){ works. Now problem is error messages appears on keyup if condition is not fulfilled but does not disappear if condition is fulfilled until I go to next input leaving some error so that inputs error message appears. So what changes I need to make in my code so that error message appearing on keyup disappera as soon as that condition is fulfilled.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var title = document.getElementById('title').value;
var category = document.getElementById('category').value;
if (category == "") {
$('#er').html('Oops! Please select a category from the options.');
return false;
}
else if (title == "") {
$('#er').html('Oops! Title cannot be empty.');
return false;
}
else if (title.length > 100 || title.length < 5) {
$('#er').html('Oops! Make sure title is 5 to 100 characters long.');
return false;
}
});
});
</script>

Try to .empty() the error message initially in the event handler,
$('input').keyup(function() {
var title = document.getElementById('title').value;
var category = document.getElementById('category').value;
var error = $('#er').empty();
if (category == "") {
error.html('Oops! Please select a category from the options.');
return false;
}
else if (title == "") {
error.html('Oops! Title cannot be empty.');
return false;
}
else if (title.length > 100 || title.length < 5) {
error.html('Oops! Make sure title is 5 to 100 characters long.');
return false;
}
});
});

Related

Jquery clear/reset form that i fill

ex I have 2 form input and 1 select form, when I select A 1 of the form hide and auto reset/clear.
basiclly i've done hide logic, but i can't reset it.
here's my code :
var employedTypeOption = $('#employedType-option');
employedTypeOption.on('change', function() {
if (employedTypeOption.val() == 1) {
$('#hourly-rate, #parttime-panel').show();
$('#basic-salary').hide();
} else if (employedTypeOption.val() == 0){
$('#basic-salary').show();
$('#hourly-rate, #parttime-panel').hide();
}
});
any idea ?
You can find all the text fields and textareas inside your form and reset their values. Like the following.
var employedTypeOption = $('#employedType-option');
employedTypeOption.on('change', function() {
if (employedTypeOption.val() == 1) {
$('#hourly-rate, #parttime-panel').show();
$('#basic-salary').hide();
$('#yourFormID').find('input[type="text"], textarea').val("");
} else if (employedTypeOption.val() == 0){
$('#basic-salary').show();
$('#hourly-rate, #parttime-panel').hide();
$('#yourFormID').find('input[type="text"], textarea').val("");
}
});

Jquery focusout runs several time by each mouse out click

I try to validate the textbox by mouse out in jquery, my code is running by any mouse out means it shows Enter valid Email. several times, any time that I click outside the textbox.
This is my code:
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
my code is not working when it is outside the document.ready.
This is what I get when I run by each time I click:
$(this).after('<div class="Required">Enter valid Email.</div>');
this will add a new after every focus out of the input box.
Instead have a placeholder div below the text box.
<div id="emailErrorMsg"></div>
and do
$('#emailErrorMsg').html('Enter valid Email.');
this will also let you add more error messages.
Remove the div before you add one to prevent repeats.
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
if($(this).next().hasClass('Required'))
$(this).next().remove();
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
I have implemented some code to validate text box and insert error div after the element if entered value is not valid.
I hope below code will solve your problem
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
var errorLabel = errorsFor(this);
$(this).addClass('ChangetoYellow');
if(errorLabel.length > 0){
$(errorLabel).show();
}
else {
$(this).after('<div for='+ this.name +' class="required">Enter valid Email.</div>');
}
return false;
} else {
$(this).next(".required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
function errorsFor( element ) {
var name = idOrName(element);
return $('.required').filter(function() {
return $(this).attr("for") === name;
});
};
function idOrName( element ) {
return element.name ? element.name : element.id || element.name;
};
});
Test sample code
Try This one first remove previous error messages and add it.
JS
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).parent().find(".Required").remove();
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).parent().find(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
For Simple Example Fiddle (if u want add the regular expression and test it) -
http://jsbin.com/pujemay/edit?html,js,output

Return through all functions

Is it possible to return through multiple functions?
I have a jQuery on click function with a $.each loop in it. In the $.each loop I test for various conditions, and if not met display an alert message and then return. Here is a cut down version of my code:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
However the return will only break that loop of the $.each loop, and start the next loop. I would like to not only break the $.each loop, but return from the on click function entirely.
Is this possible?
If so, how can I achieve this?
To exit from $.each you should return false
To exit from event handler function you should use return
As per your requirement you can do little like below,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Check out the docs for jQuery.each():
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same
as a continue statement in a for loop; it will skip immediately to
the next iteration.
Essentially, use return false; instead of just return;.

jQuery to validate a form (check for atleast 10 characters and certain value)

On my webpage I have a form where a user enters information for their article. Right now I use jQuery to check if the entered values are not empty, if they are I show an error message.
Current validation
//Story Form
$('.error').hide(); //Hide error message initially
$(".button").click(function() { //On button click
$('.error').hide();
var title = $("input#sc_title").val();
if (title == "") { //if title is empty
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
});
Right now it only checks if title == "". How would I edit the code to also check if there are at least 10 characters entered e.g. if title is empty and less than 10 chars are entered, show an error?
if user puts 20 space character in the title field in that case title.length returns 20 and it satisfy true condition so you can use jquery trim also
if ($.trim(title) == "" || $.trim(title).length < 10) {
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
this should do it:
if(title.length < 10)
here's your code edited:
$('.error').hide(); //Hide error message initially
$(".button").click(function() { //On button click
$('.error').hide();
if ($("input#sc_title").val().length < 10) {
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
});
Change your if to check the length instead - this will check anything less than 10 - ie empty too :
if (title.length < 10) {
// Show error message
}
Really simple example : http://jsfiddle.net/GFjpg/1/

JQuery Validation Problem

I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:
$('#fieldId').blur(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
$(this).focus();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
It sort of works but it moves the cursor to the next field and not the one I refocused on.
You can try this:
$('#fieldId').blur(function(evt) {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
this.focus();
evt.preventDefault();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:
var self = this;
setTimeout(function() { self.focus(); }, 1);
It's kind-of a hack but it should also work.
edit — #Gus is right about which "focus()" to call
The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.
Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().
$('#fieldId').change(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId').text('You must enter a value in this field').show();
this.focus();
} else {
if ($(this).is('.error')) {
$(this).removeClass('error');
$('#errorDivId').hide()
}
}
});

Categories

Resources