shyamm
shyamm

Reputation: 550

passing variable value in jquery

I've written a code in jQuery as follows

$(document).ready(function() {
  $("li").click(function() {
    var str = $(this).index();
    alert(str);
    $("#headdiv div:nth-child(" + str + ")").addClass("product-active");

  });
});

I want to pass the value stored in the str variable as a nth child index number. Where i'm doing wrong?

Upvotes: 0

Views: 54

Answers (3)

M3ghana
M3ghana

Reputation: 1271

We are creating a variable and appending the text with the str value and then using that string in the jQuery.

$(document).ready(function() {
      $("li").click(function() {
        var str = $(this).index();
        alert(str);
        //Create a new variable
       var buildStr = "#headdiv div:nth-child(" + str + ")";
        $(buildStr).addClass("product-active");

      });
    });

Upvotes: 0

Purvik Dhorajiya
Purvik Dhorajiya

Reputation: 4870

You should add str++.

Because the str keyword is creating a new variable every time in your every load so global variable str is not getting updated/incremented.

$(document).ready(function() {
  $("li").click(function() {
    var str = $(this).index();
    str++;
    $("#headdiv div:nth-child(" + str + ")").addClass("product-active");

  });
});
.product-active {	
	background-color: green !important;
}
.not-active{
  background-color: red;
  height: 50px;
  margin-right: 5px;
  width: 50px;
  border-radius: 50%;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Click Me</li>
  <li>Click Me</li>
  <li>Click Me</li>
</ul>
<div id="headdiv">
  <div class="not-active"></div>
  <div class="not-active"></div>
  <div class="not-active"></div>
</div>

Upvotes: 0

Ionut Necula
Ionut Necula

Reputation: 11472

Increment the str variable with 1 everytime you click. See the working snippet below:

$(document).ready(function() {
  $("li").click(function() {
    var str = $(this).index();
    str++;
    //console.log(str);
    $("#headdiv div:nth-child(" + str + ")").addClass("product-active");

  });
});
.product-active{
  color: #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>List element</li>
  <li>List element</li>
  <li>List element</li>
  <li>List element</li>
  <li>List element</li>
</ul>
<div id="headdiv">
  <div>some div</div>
  <div>some div</div>
  <div>some div</div>
  <div>some div</div>
  <div>some div</div>
</div>

Upvotes: 1

Related Questions