开发者

remove value from the list

开发者 https://www.devze.com 2023-04-02 16:41 出处:网络
I have a list of checkboxes. Upon clicking on each of the checkboxes i amadding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the ch

I have a list of checkboxes. Upon clicking on each of the checkboxes i am adding the value to the hidden variable. But the question is if I want to remove the value from the list upon unchecking the checkbox .开发者_JAVA百科 How this piece cab be done

here is the hidden form variable

<input name="IDList[]" type="hidden" id="IDList" value="" /> 

and the jquery

$(".myCheckboxClass").change(function() {
    var output = 0;
    $(".myCheckboxClass").change(function() {
        if ($(this).is(":checked")) {
            output += ", " + $(this).val();
        } else {
            output = $.grep(output, function(value) {
                return value != $(this).val();
            });
        }
        $("#IDList").val(output);
    });
});


Something like this: (demo) http://jsfiddle.net/wesbos/5N2kb/1/

we use an object called vals to store the info. ADding and removing as we check/uncheck.

var vals = {};

$('input[type=checkbox]').click(function() {
    var that = $(this);
    if (that.is(':checked')) {
        console.log(this.name);
       vals[this.name] = "In your Object";
    }
    else {
        delete vals[this.name]; 
    }
    console.log(vals);

});


Following your logic, you could do this:

$('#IDList').data('value', []);

$(".myCheckboxClass").change(function() {
    var list = $('#IDList').data('value');

    if ($(this).is(":checked")) {
        list.push($(this).val());
    } else {
        var indexToRemove = list.indexOf($(this).val());
        list.splice(indexToRemove, 1);
    }
    $('#IDList').val(list);
});

But if you only care about the value of #IDList upon data submission or other actions, you probably want to consider an alternative approach: collating the checked values when you need them.

$('#form').submit(function() {
    var list = $('input.myCheckboxClass:checked', this).map(function() {
        return $(this).val();
    }).get();

    $('#IDList').val(list);
});

See both of the above in action: http://jsfiddle.net/william/F6gVg/1/.

0

精彩评论

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