简体   繁体   中英

Remove “comma” separator after last element

I have the below code.

$(document).ready(function(){

    $('input[type="checkbox"]').click(function(){
      elem = $(this);
      part = $(this).attr("data-part-name");
      //alert(part);
      selected_options = "";
      $('.' + part).each(function () {
          if ($(this).is(":checked")) {
            selected_options +=  $(this).attr("data-option-name") + ' <b>,</b> '
          }
        });
        $("#part_child_" + elem.attr("data-part-id")).html(selected_options);
    });
});

If you see I am adding a "comma" to selected options. Now problem is it adds comma even after the last element.

How can I remove the last comma

.map() will a perfect fit for this. Also you can filter the checked items using :checked and filter

$(document).ready(function () {

    $('input[type="checkbox"]').click(function () {
        var elem = $(this);
        var part = $(this).attr("data-part-name");
        //alert(part);
        var selected_options = $('.' + part).filter(':checked').map(function () {
            return '<b>' + $(this).attr("data-option-name") + '</b>'
        }).get();
        $("#part_child_" + elem.attr("data-part-id")).html(selected_options.join(', '));
    });
});

You can use the index of iteration to compare with length of parts element and do the decision whether a comma needs to be added or not.Modify the code to:

var totalparts=$('.' + part).length;
$('.' + part).each(function (i) {
if ($(this).is(":checked")) {
 selected_options +=  $(this).attr("data-option-name") + totalparts!=(i+1) ?' <b>,</b> ':'';
}});

替换这条线

$("#part_child_" + elem.attr("data-part-id")).html(selected_options.replace(/[\<\>\,b\/\s]+$/,''));

Just remove last , substring from the string,

if(selected_options.length > 0){
  selected_options = selected_options.slice(0,-1)
}
$("#part_child_" + elem.attr("data-part-id")).html(selected_options);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM