0

I have many textarea,I want to check input length. if not longer than 10 words, can't submit. It will alert,but still submit.

function checkinput(){
  $('.TextArea').each(function() {
      var textl = $(this).val().length;
      if ( textl < 10 && (EndTime.getTime()-Time != 0)) {
          window.alert ( "answer need large 10 word!" );
          return false;
      }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <form method="POST" action="answer.php" id="form" onsubmit="return checkinput();">
吳宣旻
  • 13
  • 3
  • Does this answer your question? [JavaScript code to stop form submission](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission) – stvn Jul 10 '20 at 10:08

2 Answers2

0

Add event.preventDefault() for cases when the function is returning false;

function checkinput(event){
  $('.TextArea').each(function() {
      var textl = $(this).val().length;
      if ( textl < 10 && (EndTime.getTime()-Time != 0)) {
          event.preventDefault();
          window.alert ( "answer need large 10 word!" );
          return false;
      }
  });
  return true;
}
Prakhar
  • 1,445
  • 9
  • 15
0

function checkinput() {
  //create an event listener for click on your submit button 
  $('#submit').click(function(e) {
    // define a variable to hold textareas
    let $Textarea = $('.TextArea');
    // run a loop on each textarea
    $Textarea.each(function(i, v) {
      // variable for each instance of textarea being triggered using keyword this
      let input = $(this).val();
      // split the value at each word using a blank space
      let words = input.split(' ');
      // check the length of the split array and see if there is 10 values present
      if (words.length < 10) {
        window.alert("Textarea " + i + " - answer need large 10 word!");
        // preventDefault() keeps the form from submitting and refreshing the DOM    
        e.preventDefault();
        return false;
      }
    });
  });
}


checkinput();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form method="POST" action="answer.php" id="form">
  <textarea class='TextArea'></textarea>
  <textarea class='TextArea'></textarea>
  <textarea class='TextArea'></textarea>
  <textarea class='TextArea'></textarea>
  <button id='submit'>Submit</button>
</form>
dale landry
  • 7,831
  • 2
  • 16
  • 28