简体   繁体   中英

How to perform two action while click a button in HTML with js?

       <!DOCTYPE html>
       <html>
           <body>
               <h2>DATE&TIME</h2>
               <button type="button" 
               onclick="document.getElementById('sun').innerHTML = Date()">
               View Date</button>
                <p id="sun"></p>
              <button type="button"
              onclick="document.getElementById('sun').innerHTML = ' 
              '";"document.getElementById('sun1').innerHTML = 'Press to 
              View'";>Clear</button>
                 <p id="sun1"></p>
            </body>                                         
        </html>

I want to perform two action while button is clicked. My above code was not work. Please give solution.

Just call a local javascript function

 <button type="button" onclick="myFunction();">Clear</button>

<script>
function myFunction()
{
    document.getElementById('sun').innerHTML = '';
    document.getElementById('sun1').innerHTML = 'Press to View';
}

</script>

If you have more than 1 lines go separate user define function using script tag

 <!DOCTYPE html> <html> <head> <script> function clearbtn(){ document.getElementById('sun').innerHTML =''; document.getElementById('sun1').innerHTML = 'Press to View'; } function dateTime(){ document.getElementById('sun').innerHTML = Date(); document.getElementById('sun1').innerHTML = ''; } </script> </head> <body> <h2>DATE&TIME</h2> <button type="button" onclick="dateTime()">View Date</button> <p id="sun"></p> <button type="button" onclick="clearbtn()">Clear</button> <p id="sun1"></p> </body> </html>

  • First of all, avoid inline javascript !
  • Gives your button an unique ID

    <button type="button" id="datebutt">View Date</button>

    <p id="sun"></p>

    <button type="button" id="clearbutt">Clear</button>

    <p id="sun1"></p>

  • Then in your script you can do

    <script>

    document.getElementById("datebutt").addEventListener("click",function(){

     document.getElementById('sun').innerHTML = Date()`

    },false);

    document.getElementById("clear").addEventListener("click",function(){

     document.getElementById('sun').innerHTML = ''; document.getElementById('sun1').innerHTML = 'Press to View';

    },false);

    </script>

I have the best solution for this

In js page :-

function do(){
 // your code here
}
function do_more(){
 // your code here
}

In Html page :-

<button onclick='do();do_more();'>Button</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM