Umesh Awasthi
Umesh Awasthi

Reputation: 23587

adding css style to selected input fields using Jquery

How can I set css style on page load to certain input boxes using jquery something like

$(document).ready(function() {
    $("input, textarea").addClass("idle");
    $("input, textarea").focus(function() {
        $(this).addClass("activeField").removeClass("idle");
    }).blur(function() {
        $(this).removeClass("activeField").addClass("idle");
    });
});

HTML

<input type="text" name="author" id="author" >
<input type="text" name=email id=email >

But this will add the style to each and every input and textarea which I want to avoid.

How can I apply the desired style to selective inputs/text area fields?

Upvotes: 0

Views: 2073

Answers (3)

CupOfTea696
CupOfTea696

Reputation: 1295

I suggest using only CSS to do this, instead of making two different classes you should make one class and a pseudo-class.

input, textarea{
    ...
}

input:focus, textarea:focus{
    ...
}

I created a quick example to show this: http://jsfiddle.net/Gp8Rr/1/

In case you want only one (or certain) input elements to have this, you should create a specific class in css and a pseudo class, and just assign those classes in your html.

CSS:

.styled{
    ...
}

.style:focus{
    ...
}

HTML:

<input type="text" name="author" id="author" class="switch">
<input type="text" name="email" id="email">

Another quick example of this: http://jsfiddle.net/Apd6V/

Upvotes: 0

Troy Barlow
Troy Barlow

Reputation: 313

You need to identify the inputs by id or class. In your example, you could apply your classes to the author textbox only by doing:

$("#author").addClass("idle");

Upvotes: 2

Brian Glaz
Brian Glaz

Reputation: 15676

In order to do this, you need to add something unique to each input and textarea that you want to apply your function. You could use class for example. So, give every textarea and input that you want to select the same class name, like class="switchCSS". Then you can apply your jquery like this:

$("input.switchCSS, textarea.switchCSS").addClass("idle");
//etc etc

Upvotes: 0

Related Questions