platanas20 platanas20 - 5 months ago 40
jQuery Question

Alert message when input is greater or lower than 16 digits

I have created this:

<form class="form-horizontal" method="post" action="profile.php">
<div class="form-group">
<label class="col-sm-2 control-label">Card Number</label>
<div class="col-sm-7">
<input type="text" id="card_no" class="form-control" name="card_number" maxlength="16" autofocus="autofocus">
</div>
<button class="btn btn-primary demo1" type="submit" id="submit" onclick="check()">SEARCH</button>
</div>


When the card's length is greater or lower than 16 an alert message must be displayed. So I tried this:

$('#submit').onclick(function() {
var inputlength = $('#card_no').val().length;
if (inputlength<>16) {
sweetAlert("ERROR", "Card must have 16 digits", "warning");
return false;
}
});


But it doesn't work. I also have an alert when there is NO input and works fine! Any ideas?

Prs Prs
Answer

Use if(inputlength !== 16)

$('#submit').on('click',function() {
  var inputlength = $('#card_no').val().length;
  if (inputlength !== 16) {
    sweetAlert("ERROR", "Card must have 16 digits", "warning");
    return false;
  }
});
<link href="https://cdn.jsdelivr.net/sweetalert/1.1.3/sweetalert.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/sweetalert/1.1.3/sweetalert.min.js"></script>
<form class="form-horizontal" method="post" action="profile.php">
  <div class="form-group">
    <label class="col-sm-2 control-label">Card Number</label>
    <div class="col-sm-7">
      <input type="text" id="card_no" class="form-control" name="card_number" maxlength="16" autofocus="autofocus">
    </div>
    <button class="btn btn-primary demo1" type="submit" id="submit">SEARCH</button>
  </div>
</form>