doushishi2415 2018-06-03 00:25 采纳率: 0%
浏览 165
已采纳

动态显示复选框

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 2018-06-03 01: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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?