0

jQueryを使用して、入力が指定された制限より短い場合にアラートメッセージを表示しようとしています。残念ながら、私のコードは機能していないので、あなたの助けを求めています。

これが私が使用しているコードです。

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>
4

2 に答える 2

1

に切り替えif(comwords < minwords)たいif(msgwords < minwords)


これが完全に機能するコードです。必要に応じて変更します。

<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>

このコードは正確なIDを参照します(機能していることがわかったら、これを変更できます)。文字の代わりに単語をチェックする分割関数もうまく機能します。最後に、コメントが短すぎる場合にボタンが送信されないようにします。e.preventDefault()


また、またはのいずれかを使用できることも指摘しておきます。後者はとと同等です。これにより、そのイベントがDOMを伝播(または「バブリング」)するのを防ぎます。e.preventDefault();return falsee.preventDefault();e.stopPropagation();

于 2013-01-20T15:03:41.020 に答える
1

2つの問題があります。

  1. :textareaそのような疑似セレクターはありません。
  2. comwords定義されてない。

:textareaとにかくセレクターからドロップすることができます。そして、msgwordsの代わりに使用してcomwordsください。


代わりに:

  • イベント.form()にバインドするために使用します。submitさらに、フォームの送信を防ぎます。
  • を使用して、先頭と末尾のスペースをクリーンアップしString#trimます。
  • id要素の属性を利用してください;)

これらの線に沿って:

<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;
  });
});
于 2013-01-20T15:04:40.663 に答える