【问题标题】:Change value of checkbox after ajax sucessajax成功后更改复选框的值
【发布时间】:2014-09-25 10:23:00
【问题描述】:

Ajax Jquery

​​>
 $(".myonoffswitch").live("click",function(){
 var prod_id = $(this).attr('id');
 var status = $(this).attr('value');
 var tdid =$(this).parent().prev().attr('class');
 var td = $(this).parent().prev();

 $.ajax({
        type: "POST",
        url: "<?php echo base_url().'index.php/cms/ads_status'; ?>",
         dataType: "json",
        data: {
            'prod_id': prod_id,
            'status' : status
        },
        success: function(msg)
        {
        var updated_status = msg[0].post_status;

            if(updated_status=="0" && tdid == prod_id){

                  $(".myonoffswitch").attr("value", updated_status);


            }
            if(updated_status=="1" && tdid == prod_id){

                $(".myonoffswitch").attr("value",updated_status);
            }
        }
    });

 });

HTML

  <table><tr>
 <?php foreach($get_product as $products) { ?>
 <td class="<?php echo $products->id ?>" id="on-of">
            <input type="checkbox" class="myonoffswitch" id="<?php echo $products->id; ?>" value="<?php echo $products->post_status;?>">
 </td>
 <?php } ?>
</tr></table>

您好,我在这里将复选框单击后的值更新为 0 或 1。如果复选框值为 0,则在数据库中更新为 1,反之亦然。我成功地从 ajax 获得了更新的值,当它尝试用更新的值更改复选框的值时,它会将值更改为从 foreach 循环获得的所有复选框。我想将值更改为仅具有类 .myonoffswitch 的特定复选框,在该复选框上单击它而不是所有复选框。我怎样才能做到这一点。我在 ajax 成功后使用 $(this) 代替使用 .myonoffswitch 但我没有更改值。请问会是什么错误。谢谢。

【问题讨论】:

    标签: jquery ajax json codeigniter


    【解决方案1】:

    您需要保存当前的“this”值以供以后引用:

     $(".myonoffswitch").live("click", function () {
         var $this = $(this);
         var prod_id = $this.attr('id');
         var status = $this.attr('value');
         var tdid = $this.parent().prev().attr('class');
         var td = $this.parent().prev();
    
             type: "POST",
             url: "<?php echo base_url().'index.php/cms/ads_status'; ?>",
             dataType: "json",
             data: {
                 'prod_id': prod_id,
                     'status': status
             },
             success: function (msg) {
                 var updated_status = msg[0].post_status;
                 if (updated_status == "0" && tdid == prod_id) {
                     $this.attr("value", updated_status);
                 }
                 if (updated_status == "1" && tdid == prod_id) {
                     $this.attr("value", updated_status);
                 }
             }
         });
     });
    

    我养成了使用$ 为jQuery 变量添加前缀的习惯,所以$this 似乎很合适。它还避免了一遍又一遍地使用$(this)。

    【讨论】:

    • 我想用 updated_status 更新复选框的值。如果复选框的值为 1,则将复选框的值更新为 0,反之亦然。不是复选框的选中和未选中状态。
    • 您只需要将外部的this 保存到一个变量中,因为ajax success 回调会得到一个新的this。
    • 这正是我想要的。我不知道在 ajax 成功后 $(this) 不会被保存。谢谢。
    猜你喜欢
    • 2015-02-06
    • 2016-06-15
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    相关资源
    最近更新 更多