Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  75] [ 1]  / answers: 1 / hits: 24536  / 11 Years ago, thu, september 26, 2013, 12:00:00

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>

More From » jquery

 Answers
9
  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);
});
});

[#75418] Wednesday, September 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;