Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add script to a button in HTML in same file?

This may be a basic question. I have a button which is

<button type="button">Click Me!</button>


And then I have a script which is:

<script>
alert("My First JavaScript");
</script>


To call this script I can say onclick call another php or html file. But I want to add this script to the same file instead of adding a new file. Any suggestion will be appreciated.

like image 488
Bernard Avatar asked Dec 20 '22 17:12

Bernard


1 Answers

Couple of ways:

1st

<button type="button" onclick="clickHandler()">Click Me!</button>

<script>
    function clickHandler() {
      alert("something");
    }
</script>

2nd (if you are using something like jQuery)

<button id="btn" type="button">Click Me!</button>

$('#btn').click(function() {
    alert('something')//
});

you may also do this in plain javascript.. just search for add event handler and you will get plenty of cross browser ways of doing this.

like image 98
Lucky Soni Avatar answered Jan 12 '23 21:01

Lucky Soni