Reputation: 1612
The user is supposed to enter some information in the textarea (inside p tag in my case) which is mainly strings. However, I want to stop the user from only entering whitespaces[continuous multiple whitespaces], on which I will alert him asking to type something meaningful. How do I check for this condition? Is "if there are no normal alphabets; then alert blahblah"
a working logic? How do I code this?
$("#saveText").click(function() {
var grabbed = $(".froala-element p").text();
if (grabbed === "") {
alert("No cheating :) Please type something.");
} else {
alert(grabbed);
}
});
This is all I got so far. A jQuery solution is also welcome.
Upvotes: 2
Views: 210
Reputation: 2756
Try to listen for 'blur' and 'paste' event to make sure blank characters aren't entered by user, as show below:-
http://jsfiddle.net/chetanbh/024jvy5h/
$('#type_something').on('paste', function(event){
var element = this;
setTimeout(function () {
var text = $(element).val();
if(text.trim().length <= 0) {
alert('Sorry, paste something else, not empty string');
$(element).val('');
}
}, 100);
});
$('#type_something').on('blur', function(event){
var element = this;
var text = $(element).val();
if(text.trim().length <= 0) {
alert('Sorry, type something else, not blank characters');
$(element).val('');
}
});
Upvotes: 0
Reputation: 97150
You could test against a regular expression that represents only whitespace (/^\s*$/
):
$("#saveText").click(function() {
var grabbed = $(".froala-element p").text();
if (/^\s*$/.test(grabbed)) {
alert("No cheating :) Please type something.");
} else {
alert(grabbed);
}
});
This handles regular spaces, tabs, newlines, etc., as well as the case where there's no input.
The regular expression itself decomposes as follows:
^ Beginning of the string
\s Any whitespace character
* Zero or more occurrences of previous
$ End of the string
You could alternatively turn the test around and check for the presence of at least one non-whitespace character using /\S/
, which is probably slightly more efficient.
Upvotes: 3
Reputation: 88
If the text is in 'p' tag, your code is all right, if it is textarea, it should be:
var grabbed = $(".froala-element textarea").val();
Upvotes: 0