I am trying to change the text colour of certain options in a but it is not working. none are red
var style="color:red"
$('#newuserSelect')
.append($('<option>', {
value: "0",
title: "hello",
style: style
})
.text("my text"));
http://jsfiddle.net/ZDYEd/ the colour is black when it should be red
The property name to use is "css", not "style". Also the value should be an object whose properties are the CSS properties to set.
$('#newuserSelect')
.append($('<option>', {
value: "0",
title: "hello",
css: { color: "red" }
})
.text("my text"));
You can, incidentally set the text with that initialization object too:
$('#newuserSelect')
.append($('<option>', {
value: "0",
title: "hello",
css: { color: "red" },
text: "my text"
})
);
Now, this does work , but it's important to note that when you're looking at the page with the <select>
element not "open", you're not looking at the <option>
elements. If you want the selected text to be red, then you need to also style the <select>
element itself. When there's only one <option>
, the <select>
cannot be "opened" so you never see the style of the <option>
.
I can't recall exactly but it may be the case that IE, or old versions of it anyway, won't pay attention to styles on <option>
elements. IE <select>
was implemented in a really weird way in old versions.
Actually, $(xyz).append(abc)
will return the object of xyz
not abc
. And by the way, The proper way to set the css for an element is to use .css() function. Please read here for full reference.
So I would suggest you to use .appendTo in your current context. That will fit your need. Unlike .append() , .appendTo() will return the object of xyz [ $(xyz).appendTo(abc)
]
Try this,
$('<option>', { value: "0", title: "hello" })
.appendTo('#newuserSelect')
.text('my text')
.css({color:'red'});
Why calling jQuery to create this tiny piece of HTML?
$('#newuserSelect').append(
'<option value="0" title="hello" style="color:red">my text</option>'
);
Your JavaScript is fine. You can't color individual options with CSS. This is the output of your original fiddle!
Edited: CSS Text color not taking effect in Chrome 31 for OSX Mavericks
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.