Logging user input if meets condition

Viewed 50

I am working on a discount code feature. Here's my code:

var discount = document.getElementById("disc");

function greets(){
    var input = discount.values

    if(input == "Hey"){
        console.log("heyback");
    }
}
html {
    background-image: linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%);
    text-align: center;
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
<!DOCTYPE html>
<title>Purchase A Product!</title>
<link rel="stylesheet" href="./style.css">
<body>
    <h1>Purchase A Product</h1>
    <form action="https://formsubmit.co/samyking2011@gmail.com" method="POST">
        <input type="text" name="name" required placeholder="Name?">
        <input type="email" name="email" required placeholder="Email?">
        <input type="text" name="product" id="prodbuy" placeholder="What would you like to buy?" required>
        <input type="text" name="quantity" id="quant" placeholder="Quantity?">
        <input id="disc" placeholder="Enter Discount Codes Here(Optional)">
        <button id="discapply" type="submit" onclick="greets">Apply Promo Codes</button>
        <button type="submit" id="sub">Send</button>
        </form>
</body>
<script src="./script.js"></script>

My question is, how can I log something if a user inputs something into a text box?

Note: I cannot use .value instead of .textContent. Any help with that would also be appreciated.

1 Answers

You would want to hook into that element's input event, like so:

const discount = document.getElementById("disc");

discount.addEventListener('input', ev => {
   if (ev.target.value === 'Hey') {
       console.log('heyback');
   }
});
html {
    background-image: linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%);
    text-align: center;
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
<h1>Purchase A Product</h1>

<form id="f">
    <input id="disc" />
</form>

Related