Javascript输入字段值未定义

时间:2013-09-20 18:05:52

标签: javascript jquery html dom

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

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

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

console.log(comment_value);

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

请指导。谢谢

<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 = "answer">
      answer
    </p>        
  </body>
</html>

1 个答案:

答案 0 :(得分:6)

问题在这里

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

<p>代码提供不同的 ID