0

I am having a very strange thing happening to me. I have never seen this before. I am not very knowledgeable in jQuery/Javascript, but to my untrained eye, this looks insane...

What is happening is that without the alert('hello') under the $(document).ready function, the ID-begins-with selector does not trigger (i.e., does not alert the "goodbye"). If I add the alert('hello') below the $(document).ready) function, suddenly, the alert('goodbye') words.

How is this possible?

<script type="text/javascript">
    $(document).ready(function(){
        alert('hello');
        $('a[id^="hash-"]').click(function(e){
            e.preventDefault();
            alert('goodbye');
        });
    });
</script>

I have also tried with .on():

<script type="text/javascript">
    $(document).ready(function(){
        alert('hello');
        $('a[id^="hash-"]').on('click', function(e){
            e.preventDefault();
            alert('goodbye');
        });
    });
</script>

The HTML element is initially added on page load, but can be changed if you filter the bootgrid table, hence I changed it to .on() as suggested in the comments.

<td>
    <a id="hash-1" href="#" data-row-id="1">
        <i class="zmdi zmdi-arrow-left-bottom" title="Select this site"></i>
    </a>
</td>

I then tried this (because the original <td> where the icon resides is also dynamically created):

$(document).on('click', 'a[id^="hash-"]', function(e){
    e.preventDefault();
    alert('goodbye');
});

Also unsuccessful...

Any help would be greatly appreciated.

Kobus Myburgh
  • 993
  • 1
  • 15
  • 41

1 Answers1

-3

This is working fine for me.

$(document).on('click','a[id^="hash-"]',function(e){
  e.preventDefault();
  alert('goodbye' + $(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <a id="hash-1">1</a> 
    <a id="hash-2">2</a> 
    <a id="hash-3">3</a> 
    <a id="hash-4">4</a>
Haresh Vidja
  • 7,750
  • 3
  • 22
  • 40