Gazza Gazza - 11 months ago 34
Javascript Question

Restrict certain postcodes from being entered into form input

Am using a script at the moment to prevent certain postcodes being entered into the relevant input field.

<script>
function checkForm()
{
var a=document.forms["InsertFrm"]["Postcode"].value;

if(a == "4001" || "4002") {
alert("Sorry. This Membership is only available to visitors to the Area!");
return false;
}

}
</script>


then on Form Submit, this code runs.. - no probs.

However, would like to update (using jquery still) - a warning appears on entry and not having to wait until submitting?

Answer

What you are using is plain javascript.

You may use jquery's keyup event to do what you need.

<script>
  function checkForm() {
    var a=document.forms["InsertFrm"]["Postcode"].value;
    // change your condition to this as "4002" is always true
    if(a == "4001" || a == "4002") {
      alert("Sorry. This Membership is only available to visitors to the Area!");
      return false;
    }
  }
  $(document).ready(function() {
    $('input').on('keyup', function(evt) {
      checkForm();
    });
    $('form').on('submit', function(evt) {
      checkForm();
    });
  });
</script>

replace $('input') with your input field, i.e. $('input#postcode') and
$('form') with your input field, i.e. $('form#addressform')

You also need to change your condition as in if(a == "4001" || "4002") "4002" will always be true. It needs to be if(a == "4001" || a == "4002")

You can also disable the submit button, but that's easy to overcome on the client side, so using the submit listener will be safer at this point.

Just for fun, you could also try this:

function checkForm() {
    var a=document.forms["InsertFrm"]["Postcode"].value;
    // change your condition to this as "4002" is always true
    if(a == "4001" || a == "4002") {
      alert("Sorry. This Membership is only available to visitors to the Area!");
      $('input[type=submit]').prop('disabled', true);
      return false;
    } else {
      $('input[type=submit]').prop('disabled', false);
    }
}