doushishi2415
doushishi2415
采纳率0%
2018-06-03 08:25 阅读 78

动态显示复选框

I am creating a subscribe/unsubscribe checkbox, on sign up user will be subscribed by default. if user uncheck(unsubscribe) checkbox, it will ask for confirmation in confirm() jquery function and if it return true, ajax request will update value in database, and toggle the checkbox to run subscribe function on next click (without page reload).

MY TRY

PHP

<?php if($newsletter_value){ ?>
        <input id="checkbox" type="checkbox" name="checkbox" value="<?php echo $newsletter_value; ?>" onclick="unsubscribe();" checked>
        <span class="label-text"></span>
<? } else{ ?>
        <input id="checkbox" type="checkbox" name="checkbox" value="<?php echo $newsletter_value; ?>" onclick="update_newsletter(1);">
        <span class="label-text"></span>
<? } ?>

JavaScript

function unsubscribe(){
    var c = confirm("Are you sure?");
    if(c){
            update_newsletter(0);
    }else{ $('#checkbox').prop('checked',true)}
}

function update_newsletter(newsletter){
    url = '/updateNewsletter&newsletter='+newsletter ;
    $.ajax({
        type: 'get',
        url: url,
        dataType: 'html',
        success: function() { 
            $('#success').append("<div class='alert alert-success'><i class='fa fa-check-circle'></i> You have successfully modified your subscription <button type='button' class='close' data-dismiss='alert'>&times;</button></div>");
        },
        error: function(xhr, ajaxOptions, thrownError) {
           alert(thrownError + "
" + xhr.statusText + "
" + xhr.responseText);
        }
    });
}

Problem

On first page load, page get newsletter_value from controller and show respective checkbox but once user click it and at same time again click, same function will work as on first click (no toggle in functions).

Hope you understand. and thanks for help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanhan7001 duanhan7001 2018-06-03 09:13

    I think the problem is that you never exchange the onclick function of the checkbox. Because as you stated the page is not reloaded. That means that the PHP code is not executed and the function stays the same (because PHP is executed on the server side).

    This again means that you would have to exchange the onclick function in the success callback function of the AJAX request.

    JavaScript

    // ...
    $.ajax({
        // ...
        success: function() { 
            $('#success').append("<div class='alert alert-success'><i class='fa fa-check-circle'></i> You have successfully modified your subscription <button type='button' class='close' data-dismiss='alert'>&times;</button></div>");
            $('#checkbox').attr("onclick","update_newsletter(1);");
        },
        // ...
    });
    

    The way to change the onclick function is from this post.

    点赞 评论 复制链接分享

相关推荐