mjmendes
mjmendes

Reputation: 89

Use jQuery to assign value to hidden input fields

I am trying to assign a value to a hidden field on a form which i append to a div on a buttons click.

Here is my html

<div style="margin-bottom:5px" class="comment" data-commentID="<?php echo $c->id;?>">
            <div style="border-radius:5px 5px 0px 0px;border:2px solid black;border-bottom-width:0px;padding:3px;font-weight:bold;">
                <?php echo $c->user->username?>
            </div>
            <div style="border-radius:0px 0px 5px 5px;background-color:white;padding:5px;border:2px solid black">
                <?php echo $c->comment;?>
                <button class="reply-button">Reply</button>
            </div>
</div>

And here is my jQuery function called on reply-button's click

$(document).ready(function(){
$(".reply-button").on('click',function(){
    var form = $("<form id='reply-form' action='/project/index.php/comments/postReply' method='get'></form>");
    form.append("<textarea style='resize:none' rows='4' cols='84' name='comment'></textarea>");
    form.append('<input type="hidden" name="topic_id" value="<?php echo $model->id ?>" />')
    form.append('<input type="hidden" name="comment_id" value="$(this).parent().parent().attr("data-commentID")"/>')
    form.append('<input type="submit" value="Post" />');
    $(this).parent().append(form);
    $(this).unbind();
});});

How can set comment_id's value to the data-commentID attribute?
If i alert() what i have currently set the value then i see the commentID

alert($(this).parent().parent().attr("data-commentID"));

But setting the value to that, after posting im getting the value
$(this).parent().parent().attr(

Thanks in advance :)

Upvotes: 2

Views: 690

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use string concatenation to assign the value of a js variable to a string literal

form.append('<input type="hidden" name="comment_id" value="' + $(this).closest('.comment').attr("data-commentID") + '"/>')

Upvotes: 1

Related Questions