Dynamic if/else statement with jQuery and textarea - javascript

So I'm trying to style a <textarea> tag to highlight when it has more than one character typed in. (For a contact form). When someone is filling out the form, the fields will all highlight green to let them know its valid. I'm very new to JS and jQuery in general but I'm pretty sure this is supossed to work. I can use the $('#message').addClass('valid') by itself and it will apply the class, but when I add the if/else statement, nothing works. Here is the script
\\ Begin Highlight Code
var $messageval = $('#message').val()
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else ($messageval.length = 0 ){
$('#message').removeClass('valid');
}
});
I've been googling for hours and I can't find anything to dynamically add and remove classes based on a text length variable.
Thanks

You are missing else if
if ($messageval.length != 0 ){
$(this).addClass('valid');
}
else if($messageval.length == 0 ){ //<-- Here
$('#message').removeClass('valid');
}
Basically you can just have
if ($messageval.length != 0 ){
$('#message').addClass('valid');
}
else { //<-- Here
$('#message').removeClass('valid');
}
I guess this is what you are looking for:-
$(function(){
$('#message').on('keyup', function () {
var $messageval = $.trim($(this).val()); //$.trim here to avoid whitespace preventing validation.
if ($messageval.length != 0) {
$(this).addClass('valid'); //this here represent the textarea dom element, and $(this) is the jquery wrapper.
} else {
$(this).removeClass('valid');
}
});
});
Fiddle

$(document).ready(function(){
$("#message").keyup(function(){
var messageval = $('#message').val();
if (messageval.length > 1) {
$('#message').addClass('valid');
} else {
$('#message').removeClass('valid');
}
});
});

change your code to this
$(document).ready(function(){
$('#message').trigger('change');//if you initially want to check the textarea
$('#message').on('change', function(){
var $messageval = $(this).val();
if ($messageval.length != 0 ){
if (!$(this).hasClass("valid")) {
$(this).addClass("valid");
}
}
else ($messageval.length == 0 ){
if ($(this).hasClass("valid")) {
$(this).removeClass("valid");
}
}
});
});
Cheers!

Related

validate only visible elements in form

I want to validate the form elements on click next buttoon in step form. I am using the folllowing code which is validating all the hidden fields also. Need help. Thanks in advance..
Here is my Code :
$('.msf-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
parent_fieldset.find('.is_required').each(function() {
if( $(this).val() == "" ) {
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-slct").text("Please Select an option in the list").fadeIn();
next_step = false;
}
else{
$(this).focus().css('border','0px solid #F44336');
$(".error-messages-slct").empty().fadeOut();
}
});
parent_fieldset.find('.is_required1').each(function() {
if( $(this).val() == "" ) {
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-slct1").text("Select an option in the list").fadeIn();
next_step = false;
}
else{
$(this).focus().css('border','0px solid #F44336');
$(".error-messages-slct1").empty().fadeOut();
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
$(this).next().fadeIn();
});
}
});
you can add :visible after the selectors. Use this reference..
Use it like this
Instead of going over each element of class '.is_required1' and '.is_required', you need to do it only for these element(s) which is(are) currently visible. You can use an additional class for this, or query the display property.
Taking minksmnm's suggestion into account, you could use find('.is_required:visible') instead of ``find('.is_required')` to only select the visible elements. Otherwide your find also gets the hidden ones and validates them too.

Jquery validation code for not allowed only blank space in textbox

i m looking for code in which for not allowed only blank space... for e.g i have one textbox and i have tried this
$(document).ready(function()
{
$("#mybutton").live('click',function()
{
var txt_family_name=$("#mytextbox").val();
if(txt_family_name =="" || txt_family_name ==null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
this above code i have tried and its not working. so pls help me on that.. on one of my button i m calling this above code
Example : space....with any text -- output should be not null
: space space.... any space without any other text -- output should be null
you can use the length attribute and the trim method to remove the trailing spaces, if any:
$("#mybutton").on('click',function()
{
var length = $.trim($("#mytextbox").val()).length;
if(length == 0)
{
alert("null");
}
else
{
alert("not null");
}
});
See the updated code it's working
$(document).ready(function()
{
$("#clickme").on('click',function()
{
var txt_family_name=$.trim($("#mytextbox").val());
if(txt_family_name ==="" || txt_family_name ===null)
{
alert("null");
}
else
{
alert("not null");
}
});
});
Jquery Validation : require method only check the length of the input. So it allow the blank space.The solution will be the simple change the one line code in it.
required: function( value, element, param ) {
// Check if dependency is met
if ( !this.depend( param, element ) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// Could be an array for select-multiple or a string, both are fine this way
var val = $( element ).val();
return val && val.length > 0;
}
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return value.length > 0;
}
in above code change value.length to $.trim(value).length
so simply remove the blank space
you can use regexp.
$(document).ready(function() {
$("#mybutton").bind('click', function() {
var txt_family_name = $("#mytextbox").val();
if (txt_family_name.replace(/\s/g, '') == "") {
alert("null");
} else {
alert("not null");
}
});
});
//To add method to remove blankspaces
$.validator.addMethod("blankSpace", function(value) {
return value.indexOf(" ") < 0 && value != "";
});

Checkbox is still showing true when unchecked jQuery

Ok, so I'm currently having an issue with the $.prop('checked') functionality. When unchecking some of my boxes, and using this function to read the checkboxes, all of them are still showing up as true when some of them should be showing up as unchecked. The part of the function that checks this is below, but some background: I'm using a table with input values in each td element and due to the way it's written, I'm having to gather all the info / validate / and check by using a td.each() function.
$("td", ele).each(function(idx){
var before = $('.e_content', this),
b_name = $('input:last[type!="hidden"], textarea:last, checkbox:last, select:last', this).attr('name'),
b_val = $('input[name="'+b_name+'"], select:last, textarea[name="'+b_name+'"]', this).val(),
b_chx = $('input:checkbox[name="'+b_name+'"]', this).prop('checked'),
after = function(){
before.hide();
$(ele).css("background", color);
$('td.edit', ele).show();
$('td.save', ele).hide();
$('span', this)
// WORKING ON TAKING THE VALUE OF THE .e_content FORM AND REPLACING THE SPAN WITH IT
.html(function(){
console.log(b_name+' : '+b_chx);
if(b_val != undefined && b_val != ''){
if(b_name == 'StageType'){
if(b_val == 1){ return 'Voice'; }
if(b_val == 2){ return 'Text'; }
if(b_val == 3){ return 'Email'; }
}
else if(b_name == 'qtrhour') {
return $('select', before).find(':selected').text();
}
else if(b_chx == true) { return '&check;'; }
else if(b_chx == false) { return '&cross;'; }
else {
if(before.find('input:last').prop('type') != 'checkbox')
return b_val.replace(/\n\r?/g, '<br />');
}
}
})
.show();
};
$(this).html(after);
});
The problem is with this line:
b_chx = $('input:checkbox[name="'+b_name+'"]', this).prop('checked'),
It's coming up always as true even when the checkbox has been unchecked before the save button is hit. This function fires on the .save click event. Hopefully this is enough to determine what might be going wrong.
You can try the following,
$('input:checkbox[name="'+b_name+'"]', this).is(':checked');
To avoid issues regarding to checking or unchecking checkboxes, I normally use jQuery.attr()
$(...).attr('checked')
$(...).attr('checked','checked')
$(...).removeAttr('checked')
Also sometimes I check or uncheck them binding or triggering a .click() function.

Check if input value is empty and display an alert

How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}

How do I fix two bugs for my jQuery form Validation code?

My code basically adds a class error if field is invalid and if the field is valid, the error class is removed and form is submitted normally.
I am having trouble figuring out two small bugs for the form validation code I created.
Bugs listed below:
1) If you enter the correct content within one field, and click submit, the length of the error class does not update on first submit click. It takes two submit clicks for the length to update. (view console.log)
2) If you change the content of the input field and click submit (all works well, error class is removed) BUT if you decide to delete your updated text & leave the field blank, the error class does not get re-applied.
Would be great if I can get some assistance solving this.
Please let me know if anything is unclear.
Thanks in advance:
JSFIDDLE
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'),
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error req');
}
});
console.log(req.length);
if ( req.length === 0 ) {
return true;
} else {
return false;
}
});
Like dc5 said for #2 don't remove the req class.
And for #1 - You're looking for errors (.req) before it is removed.
See this working fiddle. It is an example how your code work but maybe you can find a cleaner solution.
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'), errorCheck = 0,
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error');
}
});
errorCheck = $(this).find('.error');
console.log(errorCheck.length);
if ( errorCheck.length === 0 ) {
return true;
} else {
return false;
}
});
for #2, You are moving the 'req' class as well as the 'error' class when clearing the error. The next time through the call, the input is no longer found through your selector $(this).find('.req')
For #1 - I don't understand the problem as you have described it.
I made it easier for you, actually your code is a mess,
here is a fiddle:
Jsfiddle validate Demo
CODE:
$('#submit_form').click(function() {
var flag = 0;
var count = 0,
total = $(".req").length;
var validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$('.req').each(function(){
count++;
if($(this).attr('id')=='email') {
if(!validateEmail($(this).val())){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='name') {
if($(this).val().length < 3){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='com') {
if($(this).val().length < 3&&$(this).val()!=''){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if ( total==count&&flag<1) { alert('submit'); }
});
});
Validation rules:
name - must be bigger then 2.
email - true on pattern match function.
comment - if typed, must be bigger the 2 chars (just to understand how can it be done).
If this example is not clear or you need more help don't hesitate... I'm bored.

Categories

Resources