Reputation: 674
I am trying to display an alert message when the input is shorter than given limit, using jQuery. Unfortunately, my code isn't working, therefore, seeking your help.
Here are the codes I am using.
HTML
<input type="textarea" name="message" id="message" row="20" col="50" />
<input type="submit" name="submit" id="submit" value="Send Message" />
JavaScript
<script type="text/javascript">
jQuery(document).ready(function($) {
$("input:submit[name='submit']").on("click",function() {
var msgwords = $("input:textarea[name='message']").val().replace( /[^\w ]/g, "" ).split( /\s+/ ).length;
var minwords = 10;
if (comwords < minwords) {
alert("Your Comment is too short.");
}
});
});
</script>
Upvotes: 0
Views: 3017
Reputation: 23537
There are two problems.
:textarea
pseudo-selector.comwords
is not defined.You can drop :textarea
from the selector anyways. And use msgwords
instead of comwords
.
I would do instead:
.form()
to bind to the submit
event. Plus, preventing the form submission.String#trim
.id
attribute of your elements ;)Along these lines:
<form>
<input type="textarea" name="message" id="message" row="20" col="50" />
<input type="submit" name="submit" id="submit" value="Send Message" />
</form>
jQuery(function($) {
$("form").submit(function () {
var minwords = 10;
/* Trim leading and trailing spaces */
var message = $("#message").val().trim();
var words = message.split(/\s+/).length;
/* Disambiguous matches for an empty string */
if ((message == "") || (words < minwords)) {
alert("Your comment is too short.");
/* Prevent form submission by returning false */
return false;
}
return true;
});
});
Upvotes: 1
Reputation: 26624
You want to switch if(comwords < minwords)
to if(msgwords < minwords)
Here's your fully working code. Change as you want.
<script type="text/javascript">
/* Use $ instead of `jQuery`, it's nicer */
$(document).ready(function() {
/* Reference the button ID (it's unique...) */
$("#submit").click(function(e) {
/* Your function to replace works nicely */
var msgwords = $("#message").val().replace( /[^\w ]/g, "" ).split( /\s+/ ).length;
var minwords = 10;
if (msgwords < minwords) {
e.preventDefault();
alert("Your Comment is too short.");
}
});
});
</script>
This code references the exact ID's (you can change this once you know it's working). Your split function checking for words instead of characters also works nicely. Finally, e.preventDefault()
prevents the button from submitting if the comment is too short.
I'd also like to point out that you could use either e.preventDefault();
or return false
, with the latter being the equivalent of e.preventDefault();
and e.stopPropagation();
. This prevents that event from propagating (or "bubbling up") the DOM.
Upvotes: 1