Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

jquery - automatically change numbering on deleting a row

I want a table row having a checked checkbox to be deleted after clicking a button. I tried the following:

$(document).ready(function() {
    $('table tr').each(function(i){
        $(this).children('td:eq(0)').append(i+1);

        //button click
        $('.deletebtn').click(function(){     
            $('table input[type="checkbox"]').is(':checked')==true?$('table input[type="checkbox"]').is(":checked").parent('td').parent('tr').remove():$('table input[type="checkbox"]').parent('tr').show()
        });
    });  
});

This is not working only because of .is(":checked") in the if statement if i remove it, the code will be:

$(document).ready(function() {
    $('table tr').each(function(i){
        $(this).children('td:eq(0)').append(i+1);

        //button click
        $('.deletebtn').click(function(){     
            $('table input[type="checkbox"]').is(':checked')==true?$('table input[type="checkbox"]').parent('td').parent('tr').remove():$('table input[type="checkbox"]').parent('tr').show()
        });
    }); 
});

This code deletes all the rows, obviously because i did not indicate the checked checkbox. So it takes $('table input[type="checkbox"]').parent('td').parent('tr') as all the rows.

NOTE: Besides this, I also want the numbering alongside each checkbox to be auto-updated on deleting a row.

My fiddle: http://jsfiddle.net/3RZWt/1/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I want a table row having a checked checkbox to be deleted after clicking a button. Besides this, I also want the numbering alongside each checkbox to be auto-updated on deleting a row.

Code

$(document).ready(function () {
    //Set Numbers to span
    function AutoNumber() {
        $('table tr').each(function (i) {
            $(this).find('span').text(i);
        });
    }
    //button slick
    $('.deletebtn').click(function () {
        $('table tr').each(function (i) {
            if($(this).find('input[type="checkbox"]').is(':checked')) {
                $(this).closest('tr').remove();
            }
        });
        //After deletion
        AutoNumber();
    });
    //Call to set initially
    AutoNumber();
});

HTML, Added span to first cell

<tr>
    <td>
        <input type="checkbox" /><span></span>
    </td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...