duanduan1993
2015-02-26 01:15
浏览 85

使用jQuery为隐藏的输入字段赋值

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 :)

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongmei3869 2015-02-26 01:17
    已采纳

    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") + '"/>')
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题