Question may sound tricky because I’m new in JS programming. First let me show you code,
<ul id="myid4" class="c_select_ul">
<li>
<div class="option op_cl">
<div class="color"></div>
<p>White</p>
</div>
</li>
<li>
<div class="option op_cl">
<div class="color black"></div>
<p>Black</p>
</div>
</li>
</ul>
and JS code is
$("ul[id*=myid4] li").click(function () {
var color = $(this).text();
color = color.replace(/^s+|s+$/g, "");
console.log(color);
});
So what I want do is, access the value of variable “color” outside of click handler and and store in another variable. It can be logged inside of it as I have shown in code. I want to use it in other functions also like to send with ajax call.
I can make ajax call inside of it but, I have three other selections to make in same way and send the four values via ajax call and receive result.
thanks in advance.
3
Answers
This question is about the scope of the variable, Global vs local variable. You have declared variable inside the callback of click event, so it dies once the execution is over.
To solve this, you need to declare variable globally. You can declare that outside the callback handler.
Now, you can access the variable everywhere inside the JS file.
If you want to call AJAX once all 4 selections are made, use class selector instead of ID:
I assume you are using Jquery. You can also do sth like this.