skyrum rummy skyrum rummy - 2 months ago 8
HTML Question

Hello, Why my button B does not work?

why my Button B does not show alert popup?

Below is my codes inside separate files

.html:

<html>
<body>
<input type="button" class="popup" value="BUTTON A"/><br>
<input type="button" class="displaymeh" value="SHOW"/>
<div id="display">
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>


.php:

<?php
echo "<input type='button' class='popup2' value='BUTTON B'/>";
?>


.js:

$(".popup").on('click', function(){
alert("HELLO WORLD!");
});

$(".popup2").on('click', function(){
alert("HELLO WORLD! 2");
});

$(".displaymeh").on('click', function(){
$.ajax({
url: 'display.php',
success: function(data) {
$('#display').html(data);
}
});
});


The reason I place the button inside .php, because I'm planning to display database table inside the php and the button to manage the database such as delete.

Edit: No, this is not the same with the Difference between .on('click') vs .click() and why I already have negative downvote within 1 hour, I will never know.

Answer

You are only allowed to have 1 id of the same name per page. id attributes must be unique. You could either bind BUTTON B seperately by giving it a different ID (id="popup2") for example, or give it a class instead of an id, and use the class binder instead:

Your HTML is also invalid. Create inputs like this:

<input type="button" class="popup" value="BUTTON A" />
<br>
<input type="button" class="displaymeh" value="SHOW" />
<input type='button' class='popup' value='BUTTON B' />

The other issue is that the element simply doesn't exist on page load. You have to re-do the bindings whenever you add new HTML to the dom! Like so:

JS:

$(function() {
  //set the button bindings initially
  setButtonBindings();

  $(".displaymeh").on('click', function() {
    $.ajax({
      url: 'display.php',
      success: function(data) {
        $('#display').html(data);
        //re-set the button bindings after html has been added
        setButtonBindings();
      }
    });
  });

});

function setButtonBindings() {
  $('.popup').off("click"); //so it won't trigger multiple times
  $('.popup').on("click", function() {
    alert("I like cheese");
    return false;
  });
}

-- try to use .on("click") and such bindings from now on instead of .click();. It's more reliable and .click() and such are deprecated functions. They are even completely removed in jQuery 3.x

Comments