Justin Emmons
Justin Emmons

Reputation: 55

appending input text elements to table with checkbox event jquery

$('#form-upload :checkbox').click(function () {
    var $this = $(this);
    // $this will contain a reference to the checkbox

    if ($this.is(':checked')) {
        // the checkbox was checked
        var sku_td = $('#sku').text()
        var price_td = $('#price').text()
        var quantity_td = $('#quantity').text()

        $('#price').empty()
        $('#quantity').empty()

        var sku = $('<input type="hidden" name="sku[]" value="' + sku_td + '">')
        var price = $('<input type="text" name="price[]" value="' + price_td + '">')
        var quantity = $('<input type="text" name="quantity[]" value="' + quantity_td + '">')

        $('#sku').append(sku)
        $('#price').append(price)
        $('#quantity').append(quantity)

    } else {
        // the checkbox was unchecked

        // undo every you did when you clicked the event

    }
});

http://jsfiddle.net/koL8xe6z/2/

i want to append my input elements to the td's with #id in the checked row

is there a way to do this without making unique id's for each checkbox?

i have tried nth-child as well...

Upvotes: 0

Views: 94

Answers (1)

joshea
joshea

Reputation: 74

The main issue here is that you have multiple elements with the same id. IDs should be unique - only one element on the page should have any one particular ID.

In this case, you should be using classes instead of IDs. By changing the id="..." to class="..." on your elements and using the parent() and siblings() traversal functions in jQuery you are able to achieve the desired result: http://jsfiddle.net/wbutdz2c/

You'll notice in the jsfiddle I provided the text inputs are not properly populated with the existing values (but they are appended in the right place). To fix this, you need to make a similar change to the selectors in these lines where you grab the existing values:

var sku_td = $('#sku').text()
var price_td = $('#price').text()
var quantity_td = $('#quantity').text()

Upvotes: 1

Related Questions