I want to set a global variable in Jquery so that when I click on a list item, the id of the clicked list item becomes the value of the variable. I have the below code which is also in this fiddle.
However the way I have it: At the moment when you click the list item,the value correctly gets put in the console.log.However afterthat when I click in the demo div,the variable is reset and is undefined.
How do I get the value of id when I click on demo,to be the value of id when I click on the list item?
eg :
when I click on aaa,the value when I click on the demo box should be id-1
when I click on bbb,the value when I click on the demo box should be id-2
<div id="demo"></div>
<ul>
<li id="id-1">aaa</li>
<li id="id-2">bbb</li>
</ul>
<script>
var id;
jQuery(document).on("click", "li", function (event) {
var id =jQuery(this).attr('id') || '';
console.log(id);
$( "#demo" ).show();
});
$(function() {
$("#demo").click(function(e) {
console.log(id);
});
});
</script>
<style>
#demo {
border: 1px solid;
display:none;
height: 100px;
width: 100px;
}
</style>
var id;
jQuery(document).on("click", "li", function (event) {
//should not not var here, using var here will declare the variable id as a local variable in the handler function scope
id = jQuery(this).attr('id') || '';
console.log(id);
$("#demo").show();
});
$(function () {
$("#demo").click(function (e) {
console.log(id);
});
});
You are again declared id
inside the loop.
var id;
jQuery(document).on("click", "li", function (event) {
id =jQuery(this).attr('id') || '';
console.log(id);
$( "#demo" ).show();
});
change
var id =jQuery(this).attr('id') || ''; to
id =jQuery(this).attr('id') || ''; inside the loop.
This is because you re declare var id
var id; // GLOBAL
jQuery(document).on("click", "li", function (event) {
var id =jQuery(this).attr('id') || ''; // LOCAL TO THIS BLOCK
so just use Global variable ,
var id; // GLOBAL
jQuery(document).on("click", "li", function (event) {
id =jQuery(this).attr('id') || ''; // Use GLOBAL id here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With