0

How can I make .click() in jquery, but name of div id is in array (after calling .each() function)?

I have code like this:

<!DOCTYPE html>
<html>

<head>
  <title>Test website</title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>

<body>
  <div id="first_div_id" class="div_class"><button type="button">Button no 1</button></div>
  <div id="second_div_id" class="div_class"><button type="button">Button no 2</button></div>

  <script>
    var ArrayWithDivId = [];

    $(document).ready(function() {
      $('.div_class').each(function() {
        ArrayWithDivId.push(this.id); //Add div id to array
      });
    });

    $(ArrayWithDivId[0]).click(function() {
      alert("Button no 1 clicked");
    });

    $(ArrayWithDivId[1]).click(function() {
      alert("Button no 2 clicked");
    });
  </script>
</body>

</html>

but there is something wrong with:

$(ArrayWithDivId[0]).click(function() {
    alert("Button no 1 clicked");
});

It can't display that alert.

How to fix it?

ptrxpl
  • 9
  • 2
  • 1
    use `class` for click event instead of `id` in that scenario exp : `div_class` – Devsi Odedra Jan 19 '21 at 09:54
  • Your code changes the `ArrayWithDivId` array in an asynchronously fired callback but expected to see the changes synchronousy. See [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) and [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/8376184) – FZs Jan 19 '21 at 09:56
  • use $("#"+ArrayWithDivId[0]) use # for ID – Sandeep K. Jan 19 '21 at 09:56
  • @FZs this isn't async code. The click event handlers are just being bound before the DOM has loaded. – Rory McCrossan Jan 19 '21 at 10:03
  • @RoryMcCrossan From the perspective of JS, DOM loading **is** asynchronous (it cannot continue while synchronous code runs), that makes the callback called back asynchronously. – FZs Jan 19 '21 at 10:22

3 Answers3

2

There's two issues with your code. Firstly to be a valid selector you need to append # to the start of the id you push in to the array. Secondly, the click event handlers need to be placed inside the document.ready handler. Try this:

var ArrayWithDivId = [];

$(document).ready(function() {
  $('.div_class').each(function() {
    ArrayWithDivId.push('#' + this.id); //Add div id to array
  });

  $(ArrayWithDivId[0]).click(function() {
    alert("Button no 1 clicked");
  });

  $(ArrayWithDivId[1]).click(function() {
    alert("Button no 2 clicked");
  });
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<div id="first_div_id" class="div_class"><button type="button">Button no 1</button></div>
<div id="second_div_id" class="div_class"><button type="button">Button no 2</button></div>

That being said, the code is not optimal at all. You can simply attach the event handler to the $('.div_class') selector and use the this keyword, or the target property of the event, within the handler to refer to the clicked element:

jQuery($ => {
  $('.div_class').on('click', e => {
    console.log(e.target.textContent + ' clicked');
  });
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<div id="first_div_id" class="div_class"><button type="button">Button no 1</button></div>
<div id="second_div_id" class="div_class"><button type="button">Button no 2</button></div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

Please try this,

$("#"+ ArrayWithDivId[0]).on('click', function() {
    alert("Button no 1 clicked");
});

Also please move your click function into document.ready function.

<script>
    var ArrayWithDivId = [];

    $(document).ready(function() {
      $('.div_class').each(function() {
        ArrayWithDivId.push(this.id); //Add div id to array
      });
    console.log(ArrayWithDivId);

    $("#"+ArrayWithDivId[0]).click(function() {
      alert("Button no 1 clicked");
    });

    $("#"+ArrayWithDivId[1]).click(function() {
      alert("Button no 2 clicked");
    });
    
});
  </script>
-1

You are missing this one.

$(`#${ArrayWithDivId[0]}`).click(function(){
 alert("Button no 1 clicked");
})
imh1j4l
  • 95
  • 5