0

I am trying to fetch the color of a list item on clicking it. I want to put some constraint on it when the color is red, say. How to do it,I am not getting it.

if($("#listbox option:selected").css("color")=="red"){
}

I have a listbox with some items of red color. I want to stop user from selecting those red color items.

Please help me.

edge
  • 257
  • 4
  • 20

2 Answers2

1

As Pete suggested, use data attribute which is better and easy way: http://jsfiddle.net/aamir/tq9W8/5/

$('#listbox option:eq(0)').css('color', 'red').data('color', 'red');

$('#listbox').change(function () {
    if ($(this).find("option:selected").data('color') == 'red') {
        alert('color is red');
    } else {
        alert('other options');
    }
});

or you can try this: http://jsfiddle.net/aamir/tq9W8/4/

$('#listbox option:eq(0)').css('color', 'red');

function checkColorByName(ele, colorName) {
    var tempDiv = $('<div>').css("color", colorName).hide().appendTo('body');
    console.log(tempDiv.css('color'));
    var bol = tempDiv.css('color') == ele.css('color');
    tempDiv.remove();
    return bol;
}


$('#listbox').change(function () {
    if (checkColorByName($(this).find("option:selected"), 'red')) {
        alert('color is red');
    } else {
        alert('other options');
    }
});

Other wise according to this, you need to use a plugin.

Community
  • 1
  • 1
Aamir Afridi
  • 6,364
  • 3
  • 42
  • 42
0

Your code is good.

If it's not working, do console.log($("#listbox option:selected").css("color")=="red");

If it says undefined, the color attribute is not set on the option, but maybe on the #listbox. (Try $("#listbox option:selected").parent().css("color")=="red"))

FLX
  • 2,626
  • 4
  • 26
  • 57
  • He to find a way to get option color and compare with the color name. read my answer for details and also Pete detail under the question :) – Aamir Afridi May 22 '14 at 11:41