Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  83] [ 7]  / answers: 1 / hits: 64669  / 10 Years ago, thu, april 3, 2014, 12:00:00

I am running a client side validation javascript which will submit a form via an ajax post after validating the data. Here is the javascript:



$(.button).click(function() {

$(.error).hide();

var name = $(:input.name).val();
if ((name == ) || (name.length < 4)){

$(label#nameErr).show();
$(:input.name).focus();
return false;
}

var email = $(:input.email).val();
if (email == ) {

$(label#emailErr).show();
$(:input.email).focus();
return false;
}


var phone = $(:input.phone).val();
if (phone == ) {

$(label#phoneErr).show();
$(:input.phone).focus();
return false;
}

var comment = $(#comments).val();
if ((!comment) || (comment > 100)) {

$(label#commentErr).show();
$(#comments).focus();
alert(hello);
return false;
}

var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url(admin-ajax.php); ?>';
alert(info);

jQuery.ajax({

type:post,
dataType:json,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == success) {

alert(success);
}
else {

alert(fail);
}
}
});

$(:input).val('');
return false;


});


The four input fields are three text inputs for name, email and phone and then one textarea for the comments/queries section. The problem is that if I leave the textarea blank or enter over 100 characters the script does not go into the if ((!comment) || (comment > 100))
statement. I am wondering if there is a different value that gets assigned to a textarea when it is blank that is stopping the code from seeing it as empty ?


More From » php

 Answers
15

You need to check the length property of comment (also, you have a few extra parens. They won't break anything, but aren't needed).



if (!comment || comment.length > 100) {


What's currently happening is that you're trying to determine if a given string is less than a number, which is quite silly, so JS declares it false. Checking comment.length compares it to a number, which is what you wanted it to do.



!comment works because an empty string is falsy, though what you think is empty might not be (for instance, a string with a space is non-empty: ' '). Use .trim() to eliminate that pesky whitespace:



if (!comment.trim() && comment.length > 100)


(as a side note, none of the above requires jQuery, it's all JavaScript)


[#71628] Wednesday, April 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arielle

Total Points: 373
Total Questions: 105
Total Answers: 96

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
;