Javascript Event Handling of Buttons Using onclick Attribute & AddEventListner Method Full Example For Beginners

 

 

index.html

 

 

By using onclick Attribute

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Onclick event handling of buttons in html and javascript</title>
</head>
<body>
    <h1>Javascript Onclick event handling</h1>

    <form>
        <input type="text" id="username" placeholder="Enter your username">
        <input type="password" id="password" placeholder="Enter your password">
        <button onclick="checkFields(event)">Submit</button>
    </form>
    <div id="result">

    </div>
</body>
<script>
    function checkFields(e){

        // prevent the auto submission of the form

        e.preventDefault()

        console.log("Validating data")

        if(document.getElementById('username').value === "" || document.getElementById('password').value === ""){
            alert("Please enter all the fields")
        }
        else{
          var result =  document.getElementById('result')

          result.innerHTML = "You have entered the username " + document.getElementById('username').value + "and password is " +
          document.getElementById('password').value
        }

    }
</script>
</html>

 

 

By Using AddEventListener() Method

 

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>javascript onclick validation</title>
</head>

<body>
<h1>Javascript Onclick event handling</h1>

<form>
    <input type="text" id="username" placeholder="Enter your username">
    <input type="password" id="password" placeholder="Enter your password">
    <button id="button">Submit</button>
</form>
<div id="result">

</div>
</body>

<script>
    var button = document.getElementById('button')

    // event listener to any dom element

    button.addEventListener('click',function(e){
        e.preventDefault()

        console.log("Validating data")

        if(document.getElementById('username').value === "" || document.getElementById('password').value === ""){
            alert("Please enter all the fields")
        }
        else{
          var result =  document.getElementById('result')

          result.innerHTML = "You have entered the username " + document.getElementById('username').value + "and password is " +
          document.getElementById('password').value
        }
    })
</script>

</html>

Leave a Reply