Wednesday, 18 September 2013

Removing values from a TextBox based on a checkbox

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.
Thanks!

No comments:

Post a Comment