user4552957
user4552957

Reputation:

How to call a div's onclick handler when pressing Enter?

All of this code here works perfectly fine, I just want to make it more easy for the user by allowing him/her to just hit the Enter to execute the function, instead of having to click the div activating the moneyFunction().

Heres my code:

<!DOCTYPE html>
<html>

<head>
    <title> YearlyDough </title>
    <link type="text/css" rel="stylesheet" href="money.css">
</head>

<body>
    <p id="header"> Enter yearly income </p>
    <input type="text" id="textmoney">
    <div onclick="moneyFunction()" id="moneydiv"> <p id="divtext">Calculate</p> </div>
    <p id="demo"></p>
    <p id="liar"></p>

    <div onclick="reloadFunction()" id="reload"> Redo </div>

    <a href="aboutmoney.html" id="about"> About </a>


    <script>
    function moneyFunction() {
        var money = document.getElementById('textmoney').value;
        var dailyE = money/365;

        document.getElementById('demo').innerHTML = ("$" + dailyE + " " + "per day");

    if ( document.getElementById('textmoney').value == 0) {
        document.getElementById('demo').innerHTML = "ERROR";
    }
    if ( document.getElementById('textmoney').value > 100000000000) {
            document.getElementById('liar').innerHTML = "I know you aint make that much.";
    } else {
        document.getElementById('liar').innerHTML = "";
    }
    }   

    function reloadFunction() {
        location.reload();
    } 
    </script>
</body>
</html>

Upvotes: 0

Views: 2185

Answers (2)

JoeJoe87577
JoeJoe87577

Reputation: 522

$('.div').click()

Inside your keydown event will call the onclick if you have jquery included on the page.

Upvotes: 0

void
void

Reputation: 36703

var inp = document.getElementById("textmoney");
inp.addEventListener("keydown", function (e) {
    if (e.keyCode === 13) {  //checks whether the pressed key is "Enter"
        moneyFunction();
    }
});

Upvotes: 1

Related Questions