JQuery Change Background Color of Dropdown List Element Based on Title

后端 未结 4 1616
执念已碎
执念已碎 2021-01-26 18:04

In this code, it originated with just a blank table with a select tag:

提交评论

  • 2021-01-26 18:44

    this is an example put it in each function or modify it to whatever you wanna do.

    $('#e2').on('click', function(){
        var title = $(this).attr('title');
        $(this).css('background-color', title);
    });
    

    I have built it on val() but I am sure you can change it. JSFIDDLE HERE

    0 讨论(0)
  • 2021-01-26 18:56

    Given the HTML structure which you state that Select2 is generating, your selector is incorrect. The select2-selection and select2-selection--single are both applied to the same element, so the space between them needs to be replaced with a class selector; ..

    Also note that you don't need the if statement as the title matches the colour you're setting with .css(). Try this:

    $('.select2-selection.select2-selection--single span.select2-selection__rendered').each(function () {
        var title = $(this).attr('title');
        $(this).parent().css('background-color', title);
    });
    

    Working example

    0 讨论(0)
  • 2021-01-26 19:00

    You missing the . in the selector so,

    use this,

    $('.select2-selection.select2-selection--single span.select2-selection__rendered')
    

    instead of this

    $('.select2-selection select2-selection--single span.select2-selection__rendered')

    0 讨论(0)
  • 提交回复
    热议问题