开发者

checkbox - checked or unchecked with jQuery and MySQL

开发者 https://www.devze.com 2023-03-06 00:39 出处:网络
I am currently creating a system where it has to be possible to check/uncheck a checkbox. Everytime it changes 开发者_运维知识库status I need jQuery to make an AJAX call to a page, that updates the da

I am currently creating a system where it has to be possible to check/uncheck a checkbox. Everytime it changes 开发者_运维知识库status I need jQuery to make an AJAX call to a page, that updates the database.

How can I do this?


For example you can do it like this:

First you have to look if the checkbox is checked:

$("#yourSelector").live("click", function(){
        var id = parseInt($(this).val(), 10);
        if($(this).is(":checked")) {
            // checkbox is checked -> do something
        } else {
            // checkbox is not checked -> do something different
        }
});

You can load specific content via Ajax:

$.ajax({
                type: "POST",
                dataType: "xml",
                url: "path/to/file.php",
                data: "function=loadContent&id=" + id,
                success: function(xml) {
                    // success function is called when data came back
                    // for example: get your content and display it on your site
                }
});


Which bit are you stuck on? You should probably have something like this...

$('#myCheckbox').click(function() {
    var checked = $(this).is(':checked');

    $.ajax({
        type: "POST",
        url: myUrl,
        data: { checked : checked },
        success: function(data) {
            alert('it worked');
        },
        error: function() {
            alert('it broke');
        },
        complete: function() {
            alert('it completed');
        }
    });
});


Detect if checkbox is checked:

if ( $('#id').is(':checked') ) { }

This can be executed in a function that is triggered by "onchange" event.

function checkCheckboxState() {

    if ( $('#id').is(':checked') ) { 

        // execute AJAX request here

    }
}


Something like this probably?

$('.checkbox').click(function (){
    var val = $(this).is(':checked');
    $.load('url_here',{status:val});
});


<input type="checkbox" name="foo" value="bar" class="checkIt"/>

<script type="text/javascript">
    $('.checkIt').bind('click', function() {
        if($(this).is(":checked")) {
            // checkbox is checked
        } else {
            // checkbox is not checked
        }
    });
</script>

You can now have more than one checkbox.

0

精彩评论

暂无评论...
验证码 换一张
取 消