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>
You want to switch
if(comwords < minwords)toif(msgwords < minwords)Here’s your fully working code. Change as you want.
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();orreturn false, with the latter being the equivalent ofe.preventDefault();ande.stopPropagation();. This prevents that event from propagating (or “bubbling up”) the DOM.