Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Global Variable onclick in Jquery

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>
like image 846
ak85 Avatar asked Sep 26 '13 06:09

ak85


Video Answer


3 Answers

  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);
      });
  });
like image 84
Arun P Johny Avatar answered Sep 21 '22 07:09

Arun P Johny


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.
like image 29
PSR Avatar answered Sep 22 '22 07:09

PSR


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 
like image 44
Deepak Ingole Avatar answered Sep 23 '22 07:09

Deepak Ingole