Question

<div id="post">
  <form name="postComment" id="commentPost6" action="javascript:void(0);" method="post"
    target="_top" onsubmit="return commentPost(6)">
     <textarea name="comment" id="comment6" class="commentText" 
        cols="10" rows="3" accesskey="1">
     </textarea><br>
     <input type="submit" name="submit" id="commentpost" value="Submit" accesskey="2">
  </form>
</div>

this is my post div tag, i have multiple div tag with same id="post", the form and fields are dynamically generated and id of both form and textarea are unique, so that there is no problem in retriving those values, on click of submit, i call commentPost method.

function commentPost(postId)
{
    alert("Inside commentpost");
    //how to retrive/access value of textarea here

}

how to get value of textarea ?? and just in case

Yes, i know it's not valid HTML to have multiple elements with the same ID.

Was it helpful?

Solution

$('#comment'+postId).val();

Why aren't you simply using classes instead of ids? (post)

OTHER TIPS

function commentPost(postId)
{
    alert("Inside commentpost");
    aler($("#commentPost"+postId).find('textarea').val());

}

This will give you the textarea value

Revised HTML (post is now a class, javascript: removed from action):

<div class="post">
  <form name="postComment" id="commentPost6" action="" method="post"
    target="_top" onsubmit="return commentPost(this)">
     <textarea name="comment" id="comment6" class="commentText" 
        cols="10" rows="3" accesskey="1">
     </textarea><br>
     <input type="submit" name="submit" id="commentpost" value="Submit" accesskey="2">
  </form>
</div>

Javascript:

function commentPost(form)
{
    var textAreaValue = $(form).find('.commentText').val();
    console.log(textAreaValue);
}

Even better, you should start writing advanced event handlers instead of these inline ones (onsubmit="" and friends). jQuery provides great methods for this.

$('.post form').submit(function (e) {
    var textAreaValue = $(this).find('.commentText').val();
    console.log(textAreaValue);

    e.preventDefault(); //to prevent default event - which is form submission
});

Inline event handlers are good for quick tests, but they quickly lead to an unmaintainable, messy HTML source. You should follow the rule of Separation of Concerns.

Try this:

Depending if you pass the postId that matches your naming standard in that form like above you had 6.

function commentPost(postId) {
        alert("Inside commentpost");
        // One way.
        var $testAreaValue = $('textarea.commentText#comment' + postId).val();
        alert($testAreaValue);
        // second way.
        $testAreaValue = $('#comment' + postId).val();
        alert($testAreaValue);
}

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top