How to use jQuery to change the backgound color of a textbox? Thanks a lot!!!
+5
A:
Better practice is to seperate UI from logic, in your case:
$("#textboxid"). addClass("aClass");
If you really need it your way, then do the following:
$("#textboxid").css({"background-color": "color"});
Replace #textboxid
with the desired selector, and color with the desired color.
Note the following does the same for one property:
$("#textboxid").css("background-color", "color");
Dykam
2009-08-03 18:00:17
No need for hard coded presentation in js. Use Css for style, js for behaviour.
redsquare
2009-08-03 18:29:15
Fixed, it's indeed better.
Dykam
2009-08-03 18:35:37
+6
A:
Better to add a class name to the input rather than hard coding styles into your js. Presentation styles should reside in css not js.
$('#inputId').addClass('someCssClass');
redsquare
2009-08-03 18:17:26
And that is also what your are doing now. I would say you should add an semantic class, not backgroundRed, I see that as an antipattern. And maybe the code here is UI code.
Dykam
2009-08-03 18:22:26
it was just a sample....of course you should not have classes for each color. geee
redsquare
2009-08-03 18:23:23
You still should not hard code style into js. What happens when he wants a border, then a different font. End up with an ugly mess of js.
redsquare
2009-08-03 18:24:11
js for behaviour, not for adding css. Why make it more difficult that addClass?
redsquare
2009-08-03 18:34:34
The "why" is the semantic portion right? so `addClass('highlight');` would be an appropriate thing for javascript to do, and then the stylesheet would specify what that looks like. Now, you could replace "highlight" with any random description, but the function is the same.
DGM
2009-08-03 18:40:40
But your original answer showed none of these thoughts. Now your the expert;)
redsquare
2009-08-03 18:56:46