2

I've been looking everywhere for a function that would control the minimum number of words entered in the textarea and, in a case the user doesn't put the minimum number of words (250 let's say), an alert would appear once he tries to submit the message.

I am using this theme: http://www.elegantthemes.com/demo/?theme=AskIt

フォームの送信方法は次のとおりです。

<form action="<?php echo(get_permalink($post->ID)); ?>#create_new_post" method="post"> 

そして、これはテキストエリアのコードです:

<textarea name="et_newpost_content" id="et_newpost_content" class="input"><?php if ( isset( $_POST['et_newpost_content'] ) ) echo esc_textarea( $_POST['et_newpost_content'] ); ?></textarea>
4

2 に答える 2

7

言葉や文字のことですか?wordsをカウントしたい場合、非常に単純なアプローチは空白で分割し、結果の配列の長さをチェックします:

if ($("#et_newpost_content").text().split(/\s+/).length < 250) {
  alert('Message must be at least 250 words.')
}

文字を意味する場合は、はるかに簡単です。

if ($("#et_newpost_content").text().length < 250) {
  alert('Message must be at least 250 characters.')
}
于 2012-08-14T17:56:09.560 に答える
2

form タグを次のように変更します。

<form onsubmit="checktextarea()" action="<?php echo(get_permalink($post->ID)); ?>#create_new_post" method="post"> 

次に、JavaScriptで次のように入力します

function checktextarea() {

   var minLength = 15;

   var $textarea = $('#et_newpost_content');
   if($textarea.text().length < minLength) {
      alert('You need to enter at least ' + minLength ' + characters');
      return false;
   }
}

これにより、テキスト領域内のテキストの文字長が minLength に設定した値よりも大きくない限り、フォームが送信されなくなります。

編集

質問を読み間違えて、単語ではなく文字を数えました。単語 (および @João への小道具) が必要な場合、関数は次のようになります。

function checktextarea() {

   var minLength = 15;

   var $textarea = $('#et_newpost_content');
   if($textarea.text().split(/\s+/).length < minLength) {
      alert('You need to enter at least ' + minLength + ' words');
      return false;
   }
}

split関数は、正規表現を使用して textarea 内のテキストを空白文字で分割し、それを配列に入れます。次に、配列の長さをチェックして、十分な単語があるかどうかを確認します

編集2

noConflictモードで実行されている Wordpress サイトでは、スニペットは次のようになります。

function checktextarea() {

   var minLength = 15;

   var $textarea = jQuery('#et_newpost_content');
   if($textarea.text().split(/\s+/).length < minLength) {
      alert('You need to enter at least ' + minLength + ' words');
      return false;
   }
}
于 2012-08-14T17:58:02.783 に答える