点击后更改文本框背景颜色

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

如果输入正确,我试图让文本框背景颜色在单击时更改为 rgb(137,200,46),如果输入不正确,则更改为 rgb(B 231,0,100),否则保持白色。错误的颜色在错误的序列上显示正常,但即使文本框为空,我也会一直变绿,而不是粉红色(因为对于此任务,空文本框是不正确的)。例如,正确的输入是“79927398713”,而我只是输入“123”或将其留空以获得错误的输入。我尝试了

values !== ""
values !== 0
,每个都在第一个
&&
中作为
if
和添加的
if else
。我用
box
integers
尝试了同样的事情,但在这一点上我只是抓住了救命稻草。你能告诉我哪里出错了吗?请放轻松,我还是很 rgb(137,200,46).

function checkLuhn(array) {
  let nDigits = array.length;
  let nSum = 0;
  let isSecond = false;
  for (let i = nDigits - 1; i >= 0; i--) {
    let d = array[i] - '0';
    if (isSecond == true)
      d = d * 2;

    nSum += parseInt(d / 10, 10);
    nSum += d % 10;
    isSecond = !isSecond;
  }
  return (nSum % 10 == 0);
}

function verify() {
  var box = document.getElementById("cardBox");
  const values = box.value.split("");
  const integers = values.map((value) => parseInt(value.trim(), 10));
  if ((checkLuhn(integers)) && (values !== ""))
  {
    box.style.background = "rgb(137,200,46)";
  } else
  {
    box.style.background = "rgb(231,0,100)";
  }
}
<!--Debit/Credit Card input; I set the type to password as an added layer of security-->
<label for="card" data-mlr-text>Card</label>
<input type="password" id="cardBox" placeholder="Write your Credit/Debit Card here" title="Write your Credit/Debit Card number" pattern="\d{10,19}" required onfocusout=verify()>

javascript html colors background luhn
1个回答
0
投票

看起来你正在尝试用字符串检查数组。 值!==“” 其中 values 是数组,所以这将始终为真。

您需要检查 box.value !== “” 或更好 !box.value

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