2017-11-05 6 views
0

検証フォームは - JS

<!DOCTYPE html> 
<html> 
<head> 
    <title>Comments</title> 
</head> 
<body> 
    <form id="commentForm" name="commentForm" onsubmit="return(validate());"> 
     <div class="row"> 
      <div class="col-sm-12 form-group"> 
       <textarea class="form-control" id="comments" name="comments" placeholder="Leave comment..." rows="3"></textarea><br> 
       <button class="btn pull-right" type="submit">Send</button> 
      </div> 
     </div> 
    </form> 
</body> 
</html> 

ブートストラップ

を使ってコメントフォームはありだと私はJSの検証

<script type="javascript"> 
    function validate() 
    { 

    if(commentForm.comments.value == "") 
    { 
     alert("Please leave your comment!"); 
     commentForm.comments.focus() ; 
     return false; 
    } 
    </script> 

行が空の場合にチェックしますと書いたが、それがすべてでは動作しません。私を助けてください、どうすれば修正できますか?

答えて

0

修正type属性をとvalidate機能の}を逃したaddが

0

あなたはそのようcommentForm要素を取得する必要があります。text/javascriptにスクリプトタグの

function validate() { 
 
    // Actually get the DOM element on which you can test value 
 
    var commentForm = document.getElementById('commentForm'); 
 
    
 
    if (commentForm.comments.value === '') { 
 
    window.alert('Please leave your comment!'); 
 
    commentForm.comments.focus() ; 
 
    return false; 
 
    } 
 
}
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title>Comments</title> 
 
</head> 
 
<body> 
 
    <form id="commentForm" name="commentForm" onsubmit="return(validate());"> 
 
    <div class="row"> 
 
     <div class="col-sm-12 form-group"> 
 
     <textarea class="form-control" id="comments" name="comments" placeholder="Leave comment..." rows="3"></textarea><br> 
 
     <button class="btn pull-right" type="submit">Send</button> 
 
     </div> 
 
    </div> 
 
    </form> 
 
</body> 
 
</html>