beckinho
beckinho

Reputation: 33

Getting siblings value with javascript

I create a textarea and a button on a loop based on a certain condition:

while($row_c= mysqli_fetch_array($result_comments))
{
//some code goes here

<textarea type="text" id="pm_text" name="text"></textarea><br>
<button name="send_comment" id="post_comment" class="button" onClick="post_pm_comment()">Post</button>
}

Now in my function "post_pm_comment" I would like to access the text written in the textarea when the post button is clicked.

I tried this, but it only gives me the text of the first textarea and button created:

function post_pm_comment(thidid, pm_id, path, pm,getter)
{
    var pm_text = document.getElementById("pm_text").value;
}

What should I do? Thank you

Upvotes: 0

Views: 449

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

Your code is outputting an invalid DOM structure, because id values must be unique on the page. You cannot have the same id on more than one element. Remove the id values entirely, you don't need them.

Having done that, the minimal-changes answer is to pass this into your handler:

onClick="post_pm_comment(this)"

...and then in your handler, do the navigation:

function post_pm_comment(postButton)
{
    var pm_text;
    var textarea = postButton.previousSibling;
    while (textarea && textarea.nodeName.toUpperCase() !== "TEXTAREA") {
        textarea = textarea.previousSibling;
    }
    if (textarea) {
        pm_text = textarea.value; // Or you may want .innerHTML instead
        // Do something with it
    }
}

Live Example | Source

Upvotes: 3

Related Questions