views:

42

answers:

2

Hi all, I'm trying to add a class to some input elements depending on the type, so if it's type='text' iI want to add .txt class and if it's typt='button' I want to add .btn class. I tried some stuff but so luck, it adds .text to all of them:

        var text_type = $('#right input').attr('type');


        if(text_type=='text'){
            $('#right input').addClass('text');
        }
        else if(text_type=='button'){
            $('#right input').addClass('btn');
        };

How do I achieve that? Thanks in advance.

Mauro

+3  A: 
$('#right input[type="text"]').addClass('text');
$('#right input[type="button"]').addClass('btn');

Attribute equals selector.

Stefan Kendall
nice man nice +1
mcgrailm
Thx Stefan! Why I didn't think about that before!? was so easy!!! I'm so f**king stupid sometimes!
Mauro74
It took me a while to use the attribute selectors effectively. When you first think about it, the conventional form of thinking gets the type and special cases behavior. Once you start thinking in jQuery magic, things get easier.The reason your original code applied "text" to everything is that $('#right input').addClass adds the class to ALL inputs! You would need to iterate over the inputs and then compare, but that gets sloppy pretty quickly. The attribute selectors solve that exact use case.
Stefan Kendall
A: 

I think what you want to do is something like this were you add the class onto all inputs which have a type of text.

$("input[type='text']").addClass("text");

Michael Ciba