duanduan1993 2015-02-26 01:15
浏览 87
已采纳

使用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") + '"/>')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line