Mac10
Mac10

Reputation: 145

Toggling Classes on Focus/Blur

I have four list items that show as a result of user selection. When the user clicks on one of these items, the class changes from '.xx' to '.yy' (changing the background color). I also have a number of text input boxes outside of the last li .I want to be able to change the class of that last li from .xx to .yy when the input boxes have focus and/or there is text in the boxes. If there is no text or focus, then the li class is changed back to .xx.

Here is the HTML:

<li class="xx lastitem">
    </li>

<span class="iknow-form">
   <input type="text" class="iknow-input" name="entry_name">
   <input type="text" class="iknow-input" name="entry_street">
   <input type="text" class="iknow-input" name="entry_city">
   <input type="text" class="iknow-input" name="entry_state">
</span>

I have tried a few different things, but nothing seems to be working.

$('input.iknow-input').bind('focus blur', function () {
    $(this).find('.lastitem').toggleClass('yy').toggleClass('xx');
});

I know there also had to be some keyup component but I am not sure how to incorporate that. Any help would be much appreciated. Thanks!

Upvotes: 0

Views: 2698

Answers (2)

Derek Foulk
Derek Foulk

Reputation: 1902

Updated

I was missing a period in one of the selectors. I also sleaned the code up a bit. This does work. I know I said that last time, but lol. I checked again.

CSS:

<style type="text/css">
  .yy {
    background-color:#FFC;
  }
</style>

HTML:

<ul>
  <li class="xx lastitem">
  </li>
</ul>

<span class="iknow-form">
   <input type="text" class="iknow-input" name="entry_name">
   <input type="text" class="iknow-input" name="entry_street">
   <input type="text" class="iknow-input" name="entry_city">
   <input type="text" class="iknow-input" name="entry_state">
</span>

jQuery:

$(function(){

    $('input.iknow-input').focus(function(){
        turnOn();
    });

    $('input.iknow-input').blur(function(){

        $("input.iknow-input").each(function(){
            if ($(this).val() != ""){
                $(this).addClass("hasText");
            }
            else {
                if ($(this).hasClass("hasText")){
                    $(this).removeClass("hasText");
                }
            }
        });

        if ($(".iknow-input.hasText").length){
            turnOn();
        }
        else {
            turnOff();
        }

    });

    function turnOn(){
        $(".lastitem").removeClass("xx");
        $(".lastitem").addClass("yy");
    }
    function turnOff(){
        $(".lastitem").removeClass("yy");
        $(".lastitem").addClass("xx");
    }

});

Upvotes: 1

Derek
Derek

Reputation: 2735

Should be

$('.lastitem').toggleClass('yy').toggleClass('xx');

instead of

$(this).find('.lastitem').toggleClass('yy').toggleClass('xx');

Upvotes: 0

Related Questions