-1

I want to check if Zipcode text field has value of 99999 but the way it's written now gives an error.

full code: function validateStep(step){ if(step == fieldsetCount) return;

    var error = 1;
    var hasError = false;
    $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input.req:not(button)').each(function(){
        var $this       = $(this);
        var valueLength = jQuery.trim($this.val()).length;
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
    var zipAllowed = ['pa', "ca"] ; 

    if(valueLength == "" || $(this).attr('id') =='email' && !emailPattern.test($this.val()) || $(this).attr('id') == 'zipcode' && ($this.val(99999)))   

    {
            hasError = true;
            $this.css('background-color','#FFEDEF');
        }
        else
            $this.css('background-color','#fff');

    });

The EmailPattern check works fine but I can't seem to assign specific values only for the zipcode?

tbodt
  • 16,609
  • 6
  • 58
  • 83

1 Answers1

1

The form $something.val('99999') sets the value and always evaluates to true in a conditional statement (the return value is the jQuery object $something).

If you want to check/test the value, use something like if($something.val() === '99999').

You can check multiple values in the following way:

var zip = $zipcode.val();
if (zip == 0 || zip == 12345 || zip == 99999) {
    $zipcode.addClass('error');
} else {
    $zipcode.removeClass('error');
}

Note that you probably want to use == for comparisons in this particular case ('00000' == 0 is true and '00000' === 0 is false). For further reading, see Which equals operator (== vs ===) should be used in JavaScript comparisons?.

Community
  • 1
  • 1
quietmint
  • 13,885
  • 6
  • 48
  • 73
  • Thanks to both you and Yogesh! $(this).attr('id') == 'zipcode' && $this.val() == 99999) was the magic line – user2738207 Sep 01 '13 at 22:49
  • Gah.... one problem after another.. Why is it not letting me add more than one value? $(this).attr('id') == 'zipcode' && $this.val()!=('5, 6')) It seems to recognize 5 but not 6 and i've tried all sorts of combinations including ((5) || (6)) but nothing seems to be working... – user2738207 Sep 02 '13 at 01:52
  • @user2738207 Updated my answer. You need a complete condition on each side of the `||` or `&&` operators. `if(zip == 5 || 6)` always evaluates to true because it essentially means "if the zipcode is 5 or if 6 is true (non-empty)". – quietmint Sep 02 '13 at 16:54