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 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决