根据用户输入动态更改错误div

时间:2017-10-15 19:07:12

标签: javascript jquery

我想根据用户在信用卡字段中输入的位数来更改错误消息。我正在尝试用这个生成消息变量:

let numberDigit;
let creditCardMessage;

 if ($cardNumber.val().length < 13) {
   numberDigit = 'Too few digits. ';
 } else if ($cardNumber.val().length > 16) {
  numberDigit = 'Too many digits. ';
 }
creditCardMessage = numberDigit + 'Please enter between 13 and 16';

然后我想在以下函数中传递creditCardMessage变量:

function creditCardNumberEvent () {

if (!isCreditCardValid()) {
 showErrorMessage ($cardNumber, creditCardMessage, $cardNumber, 'creditCardError');
} else {
 removeErrorMessage($cardNumber, '#creditCardError');
}
}

我得到的只是第一个值 - “数字太少”。提前谢谢。

3 个答案:

答案 0 :(得分:0)

运行脚本时,可以调用返回布尔值的CardNumberValid(),这意味着您可以在if语句中使用它,例如if(CardNumberValid())

&#13;
&#13;
function CardNumberValid() {
  var valid = true;
  var CardNumber = $("#CardNumber");
  if (CardNumber.val().length < 13) {
    $("#ErrorMsg").text("Too few digits. Please enter between 13 and 16");
    valid = false;
  } else if (CardNumber.val().length > 16) {
    $("#ErrorMsg").text("Too many digits. Please enter between 13 and 16");
    valid = false;
  }
  if(valid){
    $("#ErrorMsg").text("");
  }
  return valid;
}

$('#Validate').click(function() {
  alert("The card number " + (CardNumberValid() ? "is" : "is not") + " valid.");
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="CardNumber" />
<div id="ErrorMsg" style="color:red;"></div>
<button id="Validate" type="button">Validate</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我确实想到了这一点。我按照建议创建了一个函数,并将该函数作为参数传递给另一个函数:(我现在知道它是一个回调函数)

function creditCardMessageFunction () {

let numberDigit;
let creditCardMessage;

  if ($cardNumber.val().length < 13) {
     numberDigit = 'Too few digits. ';
  } else if ($cardNumber.val().length > 16) {
     numberDigit = 'Too many digits. ';
  } else {
    numberDigit = 'Numeric Values Only. ';
}
creditCardMessage = numberDigit + 'Please enter numbers between 13 and 16.';
return creditCardMessage;
}

答案 2 :(得分:0)

我认为这是你想要实现的目标:

function logValidationMessage() {
  var cardNumber = document.getElementById('cardNumber');

  var numberDigits = null;

  if (cardNumber.value.length < 13) {
    numberDigits = 'Too few digits. ';
  } else if (cardNumber.value.length > 16) {
    numberDigits = 'Too many digits. ';
  } else {
    numberDigits = 'Card number is valid.';
  }

  console.log(numberDigits);
}

document.getElementById('btnCheckCardNumber').addEventListener('click', logValidationMessage);
<input type="text" id="cardNumber" />
<input type="button" id="btnCheckCardNumber" value="Check" />