【问题标题】:Logging user input if meets condition如果满足条件,记录用户输入
【发布时间】:2021-05-27 17:15:46
【问题描述】:

所以我正在开发折扣代码功能,尽管它进展得不太顺利。 到目前为止,这是我的代码:

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>

所以我想知道如何知道用户是否在文本输入框中输入了某个单词,如果有,请记录一些内容。你能帮忙吗?

在你说“使用 .value 而不是 .textContent”之前。它不会让我使用.value。这也是我的问题的一部分!

【问题讨论】:

  • 你在哪里使用.textContent?为什么不让你使用.value
  • 你忘了()调用函数onclick="greets()"
  • 如果用户输入 hey,代码将不起作用。 onclick 应该是 greets(),获取 value 应该是 discount.value

标签: javascript logging input


【解决方案1】:

您可能想挂接到该元素的input event,如下所示:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2015-06-27
    相关资源
    最近更新 更多