oliverbj
oliverbj

Reputation: 6052

Change css class if input has a value

How can I change the CSS class of an input field, if that input field has a value

Example:

<input name='referrer' type='text' class='input-xlarge placeholder' placeholder='Referrer' value='{$ref}'  style='width:346px;'>

Currently, I am doing like this:

if ($('#reffield').val() != ''){ $('#reffield').addClass('classname'); } 

But that doesn't have any effect, nor does it generate any error.

Upvotes: 0

Views: 2858

Answers (4)

Luca Rainone
Luca Rainone

Reputation: 16458

This code change every input class name with value != ""

$('input[value!=""]').each(function() {
    this.className = "className";
});

if you want change one specific input with a given id

<input id="reffield" value="..:" ../>

then

$('#reffield[value!=""]')[0].className = "className";

if you want change a specific input based on name

 // if ($('input[name="reffield"][value!=""]')[0])
       $('input[name="reffield"][value!=""]')[0].className = "classname"

You can read the documentation of selectors

Note: you say "change class" and not "add class". In second case you should use .addClass method instead of .className property

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

There is no ID tag found and

You need to write the script in keydown Function or some condition.

$('input').keydown(function(e){

        $("#reffield").css( { backgroundColor:"blue" } );

});

DEMO

Upvotes: 0

Sadiq
Sadiq

Reputation: 2289

You need to specify the id attribute inside the tag, like this:
<input id="reffield" name='referrer' type='text' class='input-xlarge placeholder' placeholder='Referrer' value='{$ref}' style='width:346px;'>

Your jQuery selector can't find the element with the id "reffield" based on your HTML.

Upvotes: 4

Quentin
Quentin

Reputation: 943214

#reffield is an id selector. It matches elements based on the value of their id attribute. Your input doesn't have an id attribute, you should set one:

<input id='referrer' name='referrer' type='text' 

Upvotes: 1

Related Questions