0

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?

2
  • You can target them by name or id. Can you post the HTML? Commented Jan 17, 2012 at 17:19
  • show the html and what you want to select, also look at jquery selectors: api.jquery.com/category/selectors Commented Jan 17, 2012 at 17:20

3 Answers 3

2

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");
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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/

2 Comments

He wants the CSS applied to specific elements, not just when they're being hovered over.
@j08691 then he should create a specific class and assign it to the input element he wants to have this class on. I'll edit my answer right away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.