I am looking for a textarea code that allows users to submit the form only when they write a certain number of words (say 300) in the textarea provided. In-case anyone writes lesser number of words and tries to submit the form a warning message should show up.
I tried this code based on the suggestion below but the form is still getting submitted without any warning even for three-four words. Please help.
<html>
<form action="articlesuccess.php" method="POST">
<script type="text/javascript">
function checkWordCount(){
s = document.getElementById("article").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
if (s.split(' ').length <= 300) {
alarm("not enough words...");
}
}
</script>
<p>
<label for="article">Write the article in the box below:</label> <br/>
<textarea name="article" id="article" style="width:700px; height:500px;"></textarea>
</p>
<input name="submit" id="submit" type="submit" onclick="checkWordCount()" value="Submit" /><input type="Reset" value="Reset">
</form>
</html>
I think pure html code cannot achieve your desired goal. Instead, you need to write some javascript code. Suppose your textarea has an id attribute which is set as "inputString". Then the core of javascript code will be:
function checkWordCount(){
s = document.getElementById("inputString").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
if (s.split(' ').length <= 300) {
alarm("not enough words...");
}
}
And don't forget to wire the OnClick event of the submit button with this function. Let me know if I need to specify more.
The code is borrowed from http://www.mediacollege.com/internet/javascript/text/count-words.html
I have tweaked the code a bit and it is now working. Here is an example based on the code after adjustments -
<html>
<head>
<script type="text/javascript">
function checkWordCount(){
s = document.getElementById("article").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
if (s.split(' ').length <= 300) {
alert("not enough words...");
return false;
}
}
</script>
</head>
<body>
<form action="nextdestination.php" method="POST">
<p>
<label for="article">Write the article in the box below:</label> <br/>
<textarea name="article" id="article" style="width:500px; height:400px;"></textarea>
</p>
<input name="submit" id="submit" type="submit" onclick="return checkWordCount()" value="Submit" />
</form>
</body>
</html>