sventizzle
sventizzle

Reputation: 37

use incremented class name to apply classes to a similarly named div

I'd like to manipulate a div based on a text input with a similarly named class.

for example if the input is named foo1 I'd like div1 to be manipulated and if the input was foo2 i'd like div2 to be manipulated.

here is the code snippet I am using:

var i = (i + 1);
$('.pI_nameText + (i) ').focus( function() {
    $(".nameLights + (i) ").addClass("lightOverlay"); });
$('.pI_nameText + (i) ').blur( function() {
    if ($(".pI_nameText + (i) ").val() == '') {
        console.log($(".pI_nameText + (i) ").val());
        $(".nameLights + (i) ").removeClass('lightOverlay')
    }
})

here is a fiddle for this code:http://jsfiddle.net/W99vQ/

I'm nearly there I think , as this works without the incrementing, but not with it, so it should be the syntax I'm using.

Upvotes: 0

Views: 39

Answers (2)

Mark F
Mark F

Reputation: 176

You would need to iterate over all of the elemnents and then bind your handler.

for(var j = 1; true; j++)
{
  if($('pI_nameText' + i).length == 0)
  {
    break;
  }
  $('pI_nameText' + i).focus(function(){
    $(".nameLights + (i) ").addClass("lightOverlay"); 
  });
  $('.pI_nameText + (i) ').blur( function() {
    if ($(".pI_nameText + (i) ").val() == '') {
      console.log($(".pI_nameText + (i) ").val());
      $(".nameLights + (i) ").removeClass('lightOverlay');
  });
}

But I would strongly advise agains doing it this way! By looking at your fiddle, if you have access to the html, I would possibly add another class to your pI_ elements like this:

<input class="pI_nameText1 anotherClass"></input>
<div class="nameLights1 anotherClass_Lights"></div>

then bind them all at once.

$('.anotherClass').focus(function(){
  $(this).next('.anotherClass_Lights').addClass('lightOverlay');
});
$('.anotherClass').blur(function(){
  $(this).next('.anotherClass_Lights').removeClass('lightOverlay');
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

It will be better to group the elements with a common class and use it as a selector like

<input class="pI_nameText name1"></input>
<div class="nameLights"></div>
<input class="pI_nameText name2"></input>
<div class="nameLights"></div>
<input class="pI_nameText name3"></input>
<div class="nameLights"></div>
<input class="pI_nameText name4"></input>
<div class="nameLights"></div>
<input class="pI_nameText name5"></input>
<div class="nameLights"></div>

then

jQuery(function () {
    $('.pI_nameText').focus(function () {
        $(this).next().addClass("lightOverlay");
    }).blur(function () {
        if (this.value == '') {
            $(this).next().removeClass('lightOverlay')
        }
    })
})

Demo: Fiddle

Upvotes: 1

Related Questions