简体   繁体   中英

Attribute selected option by text not value?

When clicking a table row, the row text copies up to the inputs above for editing purposes. The text copies up just fine, but I cannot get all the selects right. My text isn't the same as the value (for every select, it is for the third column), so I cannot use the .val() of the select.

I need to attribute/prop selected where text matches the beginning of text AND whether or not it is reimbursable (third column). Ideas? jsfiddle.net/7vLdxddr/14

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

                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("table").find("th").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());
                }
            });

If you do like this, you don't need to have values that equals to the text.

    $('table').on('click', 'tr', function () {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
        }
        else {
            $('tr.selected').removeClass('selected');
            $(this).addClass('selected');
        }

    // fill inputs
    $(this).closest("table").find("th").eq(0).find("input:text").val($(this).find("td").eq(0).text());

    // fill selects      
   var text = $(this).find("td").eq(1).text();
   var text3 = $(this).find("td").eq(2).text();

   $(this).closest("table").find("th").eq(1).find("select option").filter(function() {
    return $(this).text().indexOf(text) >= 0 && $(this).text().indexOf($(this).closest("table").find("th").eq(2).find('select option[value="' + text3 + '"]').text()) > 0;
}).prop('selected', true);        

   $(this).closest("table").find("th").eq(2).find('select').val(text3);

});

http://jsfiddle.net/7vLdxddr/15/

Just update the values of the select values to reflect the text coming in from the click (ie cir to circle , sq to square and it works perfectly.

http://jsfiddle.net/7vLdxddr/10/

What your code was trying to do was select a input with value circle , but the value of the circle field was cir so it was not being selected properly.

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