Search code examples
javascriptphphtmlphp-5.3

How to add JS confirm to dynamicly created button in PHP


My app's generating href dynamicly. How to add JS confirm onClick? So far I've tried this one:

echo'<a type="button" onClick="return confirm("Are you sure?")" 
class="btn btn-danger" href="delete.php?id='.$this->articleId.'" >Delete</a>';

And it doesn't work. Any ideas how to fix it? Thanks :)


Solution

  • Notice that the " is breaking the your code:

    onClick="return confirm("Are you sure?")" 
    

    That line actually splits up in to three:

    onClick="return confirm(" //Ends here because the code is from " -> "
    Are you sure? //This is nothing to the code and cannot be run
    ")" //This is another string
    

    And so the correct way to do it would be the following:

    onClick="return confirm('Are you sure?')"