Madam Zu Zu
Madam Zu Zu

Reputation: 6605

Removing values from a TextBox based on a checkbox

i populate a textbox when checkboxes are clicked, with their values (comma separated) Now i want to remove that value from the textbox when the checkbox is unchecked.

here is where i am now:

$(document).ready(function () {
    $('.checkboxes').change(function () {
        if ($(this).is(':checked')) {
            if ($('.DISTRIBUTION').val().length == 0) {
                var current = $('.DISTRIBUTION').val() + $(this).val() + ",";
            }
            else {
                var current = $('.DISTRIBUTION').val() + "," + $(this).val();
            }               
        }
        else if ($(this).not(':checked')) {
            var current = $('.DISTRIBUTION').val().replace(","+$(this).val(), "");
        }
        $('.DISTRIBUTION').val(current);
    });
});

it works great! except for the first value, which does not have a comma in front of it. how do i handle that situation? How do i find out of the value to be removed, is actually the first item in the textbox?

here's an example:

apple,pear,peach,banana

when i remove ",pear" and ",banana" it works fine, but when i get to ",apple" it does not work as apple is first and there is no comma.

NOTE: i need the textbox to add the items in the order i check them... if i rebuild the checkbox list on the fly each time, it adds them in the order they appear on the screen, instead of the order i click.

Thanks!

Upvotes: 2

Views: 1941

Answers (6)

musefan
musefan

Reputation: 48415

I would suggest just rebuilding a fresh value each time, rather than trying to insert and remove on the existing value.

The HTML used for the examples below is as follows:

<input type="checkbox" class="fruit" value="apple" />Apple
<input type="checkbox" class="fruit" value="banana" />Banana
<input type="checkbox" class="fruit" value="peach" />Peach
<input type="checkbox" class="fruit" value="pear" />Pear

Values in order of appearance

To display the values in the order they appear within the DOM, you can do the following:

function setValue() {
    var items = $(".fruit");
    var result = [];
    for (var i = 0; i < items.length; i++) {
        var item = $(items[i]);
        if (item.is(":checked")) {
            result.push(item.val());
        }
    }
    var text = result.join(",");
    $(".DISTRIBUTION").val(text);
}

Here is a working example

Values in order of selection

If you want to preserve the order that they are selected in, then you can do it like so:

var results = [];

$(".fruit").change(function () {
    var item = $(this).val();
    var index = results.indexOf(item);
    if ($(this).is(":checked")) {
        if (index == -1) {
            results.push(item);
        }
    } else {
        if (index > -1) {
            results.splice(index, 1);
        }
    }
    $(".DISTRIBUTION").val(results.join(","));
});

Here is a working example

Upvotes: 4

Panos Bariamis
Panos Bariamis

Reputation: 4653

try

$('.checkboxes').on('change', function() {
    var values = $.map($('.checkboxes:checked'), function(n, i) {
        return n.value;
    }).join(',');

    $('.DISTRIBUTION').val(values);
});

see http://jsfiddle.net/2xebK/1/

reserve order

var checkedItems = [];

$('.checkboxes').on('change', function() {
    var value = $(this).val(),
        pos = $.inArray(value, checkedItems);

    if (pos == -1) {
        checkedItems.push(value);
    } else {
        checkedItems.splice(pos, 1);
    }

    $('.DISTRIBUTION').val(checkedItems.join(','));
});

see http://jsfiddle.net/2xebK/3/

Upvotes: 0

Madam Zu Zu
Madam Zu Zu

Reputation: 6605

got it!

 $(document).ready(function () {
        $('.checkboxes').change(function () {
            if ($(this).is(':checked')) {
                if ($('.DISTRIBUTION').val().length == 0) {
                    var current = $('.DISTRIBUTION').val() + $(this).val() + ",";
                }
                else {
                    var current = $('.DISTRIBUTION').val() + "," + $(this).val();
                }
            }
            else if ($(this).not(':checked')) {
                if ($('.DISTRIBUTION').val().indexOf($(this).val()) == 0) {
                    var current = $('.DISTRIBUTION').val().replace($(this).val()+",", "");
                }
                else {
                    var current = $('.DISTRIBUTION').val().replace("," + $(this).val(), "");
                }
            }
            $('.DISTRIBUTION').val(current);
        });
    });

Upvotes: 0

Falci
Falci

Reputation: 1873

You can rewrite all text: http://jsfiddle.net/kkYaZ/1/

$('.checkboxes').change(function () {
    var value = [];

    $(".checkboxes:checked").each(function(index, elem){
        value.push( $(elem).val() );
    });

    $(".DISTRIBUTION").val(value);    

 });

Upvotes: 0

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

Make it to two replace statements. Like

var current = $('.DISTRIBUTION').val().replace($(this).val(), "").replace(",","");

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

It's much easier to rebuild the state completely, rather than splice/delete items from the array. Try this;

$('.checkboxes').change(function () {
    var values = $('.checkboxes:checked').map(function() {
        return this.value;
    }).get().join(',');
    $('.DISTRIBUTION').val(values);
});

Example fiddle

Upvotes: 2

Related Questions