简体   繁体   中英

How to append some extra text in the div tag

I am trying to take the label text of the checkbox which are checked and I trying to append in the span tag,
When user click the the ok button in the popUp
Here it is not working. Here is my jsfiddle

My script is:

$('.modal-footer .preSuccess').click(function(){            
            var parentElement=$(this).parent().parent().attr('id');
            $('#'+parentElement+ '.modal-body  input[type="checkbox"]').each(function(){
                var pre =$(this).next('label').text();
                if($(this).is(':checked')){
                    $('.'+parentElement+'Pre').append('<span>'+pre+'</span>'); 
                }   
            });

        });

Try

$('.modal-footer .preSuccess').click(function () {
    var modal = $(this).closest('.modal');
    var parentElement = modal.attr('id'); // issue here, use closest to get a parent matching the selector
    //again issue with the selector
    modal.find('.modal-body  input[type="checkbox"]').each(function () {
        var pre = $(this).next('label').text();
        if ($(this).is(':checked')) {
            $('.' + parentElement + 'Pre').append('<span>' + pre + '</span>');
        }
    });

});

Demo: Fiddle

I took a look at your code and you're missing a space when querying the checkbox:

 $('#'+parentElement+ ' .modal-body  input[type="checkbox"]')

It wasn't able to find your checkbox and couldn't find the texts.

Other than that I would advice against the .parent().parent() structure, cause it's very prone to future bugs. Maybe just call the id directly, but I'm not sure how you're using this code.

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