0

In my program I create buttons with javascript and they should start an function but they don't. If I press the button on my program the browser says "can't find variable" how can I fix it that the button starts the function.

JS-Code

$(document).ready(function(){
function myfunction() {
alert("pls");
}
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data:{status:status},
success: function(data){
    var anzahl = 1;
    status = 1;
    while (anzahl>nummer) {
      nummer++;
    $.ajax({
        type: "POST",
        url: "http://localhost/jQuery&PHPnew/Markt.N.php",
        data:{nummer:nummer, status:status},
        success: function(data){
          var Daten = JSON.parse(data);
          var Ausgabebereich = document.getElementById('main');
          var f = document.createElement("form");

          var bInhalt = document.createElement('button');
          var Inhalt = document.createTextNode("Senden");
          bInhalt.appendChild(Inhalt);
          bInhalt.setAttribute("type", "button");
          bInhalt.setAttribute("onclick", "myfunction()");
          f.appendChild(bInhalt);

          Ausgabebereich.appendChild(f);

        }

       })
      }
     }
    })
  })
  • 1
    Your issue is most likely due to the `myfunction` being scoped to the document ready. Move it outside of the document ready. It needs to be global for inline bindings – Taplar Jan 09 '20 at 20:50
  • Where you do see that error? At what point in your code does that error occur? – mwilson Jan 09 '20 at 20:50
  • @Taplar thx it works now – Hagga Nagga Jan 09 '20 at 20:53
  • Note that you can also avoid the problem (and massively improve your code) by using delegated event handlers: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Rory McCrossan Jan 09 '20 at 21:27

0 Answers0