0

Good day everyone, I need some jQuery traversal help (I can never get it exactly right). In my example below, when the user clicks on a table row (it is highlighted) this should fill the matching inputs/selects of the div#editField (being Contact Name, Responsibility and Phone). I asked for something similar here, but we were still working within the same table (http://jsfiddle.net/7vLdxddr/7/) so this is a little different.

jQuery

$('.table').on('click', 'tr', function (e) {

    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
    }
    else {
        $('tr.selected').removeClass('selected');
        $(this).addClass('selected');
    }

    for (var i = 0; i < $(this).find("td").length; i++) {
        // fill input values
        $(this).closest("#editField").find("div").eq(i).find("input:text")
        .val($(this).find("td").eq(i).text());

        // fill selects                                                           //$(this).closest("table").find("th").eq(i).find("select")
        //.val($(this).find("td").eq(i).text());
    }
});

http://jsfiddle.net/DTcHh/1015/

triplethreat77
  • 1,276
  • 8
  • 34
  • 69

1 Answers1

1

Please note I am appending the options to the select, so if you choose multiple rows, you might have to remove pre-selected options. However, if you have a pre-populated select, you just need to match the value of the option and selecting it.

$('.table').on('click', 'tr', function (e) {

    var $this = $(this);

    if ($this.hasClass('selected')) {
        $this.removeClass('selected');
    } else {
        $('tr.selected').removeClass('selected');
        $this.addClass('selected');

        var user = $this.find('td').eq(0).text(),
            responsibility = $this.find('td').eq(1).text(),
            phone = $this.find('td').eq(2).text();

        // fill input values
        $('#adduser').val(user);
        $('#responsibility').append($("<option></option>")
            .attr("value", responsibility).text(responsibility));
        $('#phone').append($("<option></option>")
            .attr("value", phone).text(phone));

    }

});

http://jsfiddle.net/DTcHh/1017/

o--oOoOoO--o
  • 770
  • 4
  • 7