无法更改输入文本框的背景

问题描述 投票:0回答:1

我正在尝试创建一个文本框,如果您提交正确的答案,文本框的背景将变为绿色,如果答案不正确,则文本框的背景将变为红色。然而,这两个选项似乎都没有发生任何事情。

<h3>
  What tree can you hold in your hand?
</h3>
<form>
  <input autocomplete="off" autofocus name="q" placeholder="Answer" type="text">
  <button type="submit">Submit</button>
</form>
<script>
  document.querySelector('form').addEventListener('submit', function(event) {
    //Stuff
    let input = document.querySelector('input[name="q"]');
    let answer = input.value.toLowerCase().trim();

    if (input.timeoutId) {
      clearTimeout(input.timeoutId);
    }

    // Compare with the correct answer
    if (answer === 'palm tree' || answer === 'a palm tree') {
      input.style.backgroundColor = '#00ff00'; // Green for correct answer
      input.timeoutId = setTimeout(function() {
        input.style.backgroundColor = '';
      }, 2000);
    } else {
      input.style.backgroundColor = '#ff0000'; // Red for incorrect answer
      input.timeoutId = setTimeout(function() {
        input.style.backgroundColor = '';
      }, 2000);
    }
    event.preventDefault();
  });
</script>

javascript html background-color rgb
1个回答
0
投票

您快到了,但忘记使用

event.preventDefault();
。此方法会阻止表单以传统方式提交,从而允许您的 JavaScript 代码按预期运行。

这是工作片段:

<h3>
  What tree can you hold in your hand?
</h3>
<form>
  <input autocomplete="off" autofocus name="q" placeholder="Answer" type="text">
  <button type="submit">Submit</button>
</form>
<script>
  document.querySelector('form').addEventListener('submit', function(event) {
  event.preventDefault();  // Prevent the default form submission

  let input = document.querySelector('input[name="q"]');
  let answer = input.value.toLowerCase().trim();

  if (input.timeoutId) {
    clearTimeout(input.timeoutId);
  }

  // Compare with the correct answer
  if (answer === 'palm tree' || answer === 'a palm tree') {
    input.style.backgroundColor = '#00ff00'; // Green for correct answer
    input.timeoutId = setTimeout(function() {
      input.style.backgroundColor = '';
    }, 2000);
  } else {
    input.style.backgroundColor = '#ff0000'; // Red for incorrect answer
    input.timeoutId = setTimeout(function() {
      input.style.backgroundColor = '';
    }, 2000);
  }
});

</script>

© www.soinside.com 2019 - 2024. All rights reserved.