2

I want to add css class dropdownliststyle to dropdown only when "please select" is selected on focus.how do i do that?

here is my jsfiddle link https://jsfiddle.net/3dj3srxp/ to that

CSS

 .DropDownStyle {
   background-color: red;
   color: white;
 }

jquery

$(document).ready(function() {
    $('input[type="text"]').each(function() {
      $(this).focus(function() {
        $(this).addClass('textBoxStyle');
      });

      $(this).blur(function() {
        $(this).removeClass('textBoxStyle');
      });
    });

    $('select').focus(function() {
        $(this).addClass('DropDownStyle');
    });

    $('select').blur(function() {
        $(this).removeClass('DropDownStyle');
      });

  });
1
  • See my updated answer...it would be better to use the 'change' function, and check the value... I have a update to your fiddle in my answer. Commented Dec 21, 2015 at 23:58

3 Answers 3

4

Let's do it in one line.

$('select').on('change', function(){
    $(this).toggleClass('DropDownStyle', $(this).val() == 'select');
});
Sign up to request clarification or add additional context in comments.

1 Comment

wish i can mark more than one solution as answer. different way of doing it.good to know. Thanks
1

You need to add an if statement to check for the value, and it would actually be better to use the change function:

$('select').change(function() {
  if ($(this).val() == "select") {
    $(this).addClass('DropDownStyle');
  } else {
    $(this).removeClass('DropDownStyle');
  }
 });

You can see the fiddle here: https://jsfiddle.net/3dj3srxp/3/

Comments

0

The focus applies only to input elements if you want to change the color of the select box maybe you will use the 'change' event:

$('select').on('change',function() {
   $(this).removeClass('DropDownStyle');

   if($(this).val() == 'select'){
     $(this).addClass('DropDownStyle');
   }
});

1 Comment

The reason for that is that kevindeleon has changed something in your HTML after I posted my answer. So I had to update my answer again. If you are doing this as validation I will advise you to check for the inserted values when the user submit the form and avoid posting the form if something goes wrong. Cheers :)

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.