Javascript 输入字段值未定义

Javascript Input field value undefined

本文关键字:未定义 字段 输入 Javascript      更新时间:2023-09-26

我遇到的问题是我无法访问我的一个文本字段的值。我知道最初加载文档时,值将是未定义的。但是当我在单击提交时访问输入字段的值时,我必须在文本框中获取确切输入的字符串。

$("#foo").submit(function(event)

但即使在此事件侦听器之后,我也无法访问该值。

console.log(comment_value);

始终显示未定义。我也使用了 val() 函数的 jquery 版本,但没有帮助。

请指导。谢谢

<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
      $(document).ready(function(){                
        $("#foo").submit(function(event){           
          var comment_value = document.getElementById("newComment").value;        
          console.log(comment_value);
          event.preventDefault();
          // $("#newcommentblock").html(&#039;<img src="a.gif"/>&#039;);                  
          request = $.ajax({
            url: "getcomment.php",
            type: "POST",
            timeout:30000,  
            dataType: "text", 
            data:{getquestionid: 12, getcomment: "comment_value"}               
          });
          alert("inside script");
          request.done(function (response, textStatus, jqXHR){
          console.log("Hooray, it worked!");
          //$("#comments").html(response);              
        });        
        request.fail(function (jqXHR, textStatus, errorThrown){               
          console.error("The following error occured: " + textStatus + ", " + errorThrown);
        });        
        request.always(function () {});
        console.log("hi inside");           
      });
    </script>
  </head>
  <body>  
    <h1> 
      question: <br> jisofqw<br>        
    </h1>
     <p id = "comments">        
      comments <br>
    </p>
    Type your comment here
    <div id = "newcommentblock">
      <p id = "newComment">  </p>
      <form  id = "foo" name = "commentbox" action = "#" >
        <input type = "text" id ="newComment"   name = "newComment">
        <input type = "submit" value = "post a comment">
      </form>
    </div>
    <p id = "answerswer">
      answer
    </p>        
  </body>
</html>

问题就在这里

<p id="newComment"></p>

为标记提供不同的 ID <p>