0

I want to use a button with OnClick that I created with JS. I can create the button and I also get the attribute on to the Button but the Button doesn't start my function he only reset the Website.

          $.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data:{status:status},
success: function(data){
    var anzahl = data;
    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("onclick", "myfunction()");
          f.appendChild(bInhalt);

          Ausgabebereich.appendChild(f);
        }

    })
}
}
})
function myfunction() {
alert("pls");
}

This is the code created in the browser

Code from the Browser

Abhinav
  • 83
  • 1
  • 10
  • 2
    If the button is inside a form and does not have type attribute set to "button" it will function as "submit" button, hence submitting and redirecting/refreshing the page. – Nawed Khan Jan 09 '20 at 18:56

1 Answers1

0

On your myfunction() add the line preventDefault() before the alert, to prevent the page to be reloaded (the default behavior of the submit - as your button is on a form), then your alert will work.

Otherwise you could add the button type on your button, as <button type="button"> to make sure the form won't make it a submit button