0

The problem which i have is that i can't access the value of one of my text field. I know that when the document is initially loaded the value would be undefined. But when i am accessing value of input field when i have clicked on submit then i must get exact entered string in text box.

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

But even after this event listener i can't access the value.

console.log(comment_value);

always shows undefined. I also used the jquery version of val() function but of no help.

Please guide. Thank you

<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
  • You have duplicate id. it will pick only the first element appearing in DOM which happens to be a p tag and it is not an input field. Commented Sep 20, 2013 at 18:10

1 Answer 1

6

Problem is here

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

Provide a different ID to <p> tag .

Sign up to request clarification or add additional context in comments.

1 Comment

Please have a read of the editing help page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.