There is a script that stops sending the form if the text field is empty.
How to make it so that if the field is empty - the form was not sent, and the textarea was made active (that is, as when clicking on it)?

From comments:
How to make more lines to turn red, but if they just clicked, they were normal?

Here is the code:

  $('form').submit(function(){ // Если textarea пустое if(!$(this).find('textarea').val()){ // отменяем отправку return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action='page' method='POST'> <textarea></textarea><br><input type='submit'> </form> 

  • $ (this) .find ('textarea'). focus ()? - Bookin
  • @Bookin yes, but how to insert into the code? - BedOmar

2 answers 2

 $('form').submit(function(){ if(!$(this).find('textarea').val()){ $('textarea').focus(); return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <textarea></textarea><br /> <input type='submit' /> </form> 

So?


 $('form').submit(function(){ if(!$(this).find('textarea').val()){ $('textarea').focus().css('border','2px solid red'); return false; } }); $('textarea').click(function(){ $(this).css('border','2px solid blue'); }); 
  • and how to make the lines turn red, but if they just clicked, they were normal? - BedOmar
  • @BedOmar - described in his answer how to make a red border - alexoander

As an addition to your question - with a red border

 $('form').submit(function() { if (!$(this).find('textarea').val()) { $('textarea').focus(); $('textarea').css("border", "1px red solid"); return false; } }); $('textarea').on("click", function(e) { $(this).css("border", "1px #aaa solid"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <textarea></textarea> <br /> <input type='submit' /> </form>