3

I tried finding some fixes, but don't seem to be finding what I'm looking for. Maybe its my wording.

So I have this form that once it submits with a 5 digit zip code it checks an array for a matching value, once its matches I want it to show a success message and if It doesn't match then return No match, but currently it returns the message as many time as the array has. I'm still fairly new to JavaScript so any help would be greatly appreciated. Thanks in Advance!

JavaScript:

<script>
function getZip(e) {
    e.preventDefault();
    var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
    var result = ["48650", "48611", "48746", "48614", "48706"];

    for (var i = 0; i < result.length; i++) {
        //console.log(result[i]);

        //if (zip.length == 5 && zip == result[i]){
        if (zip == result[i]) {
            console.log(zip + " is = to " + result[i]);
            alert('Match ' + zip);

        } else if (result[i] != zip) {
            alert("No Match1");
            console.log(zip + " is != to " + result[i]);

        } else {
            alert("No Match2");
            console.log(zip + " is != to " + result[i]);
        }
        //return false;
    }
    if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
        alert('Please enter a zip code!');

    } else if (zip.length > 5) {
        alert("Please enter a valid 5 digit numeric zip code.");

    } else if (zip.length < 5) {
        alert("Please enter a valid 5 digit numeric zip code.");

    } else if (isNaN(zip)) { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message.
        alert("Please enter a numeric value.");
    }
}
</script>

Form:

<div class="searchZip">
    <p>Please enter your zip code for availability</p>
    <form>
        <input type="text" name="zip" id="zip" placeholder="Zip Code">
        <button onclick="getZip(event);">Check</button>
    </form>
    <p id="display"></p>
</div>
3
  • 3
    Possible duplicate of javascript exiting for loop without returning Commented Nov 23, 2015 at 15:20
  • @Abhitalks which is also a possible duplicate of How to stop a for loop? :) Commented Nov 23, 2015 at 15:25
  • Thats not the only issue though, its still retunring only the first result and not getting to the others int eh array to match up Commented Nov 23, 2015 at 15:29

4 Answers 4

5

As others have said, you could use break to exit out of the loop.

I would not use a loop though. Instead, I would use the .some function to determine if there is a match:

function getZip(e) {
  e.preventDefault();
  var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
  var result = ["48650", "48611", "48746", "48614", "48706"];

  if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
    alert('Please enter a zip code!');

  } else if (zip.length > 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (zip.length < 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (isNaN(zip)) { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
    alert("Please enter a numeric value.");
  } else {
    var match = result.some(function(r) {
      return zip === r;
    });

    if (match) {
      alert('Match ' + match);
    } else {
      alert("No Match");
    }
  }
}
<div class="searchZip">
  <p>Please enter your zip code for availability</p>
  <form>
    <input type="text" name="zip" id="zip" placeholder="Zip Code">
    <button onclick="getZip(event);">Check</button>
  </form>
  <p id="display"></p>
</div>

Or, you could use indexOf for a simple match like yours.

Sign up to request clarification or add additional context in comments.

Comments

5

Use break to break out of loop.

In your case there's no need of for, use Array#indexOf to check if the array contain an element.

You can also use HTML5 pattern attribute with regex [1-9][0-9]{4}.

var result = ["48650", "48611", "48746", "48614", "48706"],
  display = document.getElementById('display');

function getZip(e) {
  e.preventDefault();
  var zip = document.getElementById('zip').value,
    message = '',
    className = 'valid';

  // Remove classes
  display.classList.remove('valid')
  display.classList.remove('invalid');

  // Check if entered valid zipcode
  if (/^[1-9][0-9]{4}$/.test(zip) === false) {
    message = 'Please enter valid 5 digit zip code';
    className = 'invalid';
  } else {
    var index = result.indexOf(zip);

    if (index > -1) {
      message = 'Zip ' + zip + ' found at index ' + index;
    } else {
      message = 'Zip not found in array';
    }
  }

  // Show message
  display.innerHTML = message;
  display.classList.add(className);
}
#zip:invalid,
.invalid {
  color: red;
}
.valid {
  color: green;
}
<div class="searchZip">
  <p>Please enter your zip code for availability</p>
  <form>
    <input type="text" name="zip" id="zip" placeholder="Zip Code" pattern="[1-9][0-9]{4}">
    <button onclick="getZip(event);">Check</button>
  </form>
  <p id="display"></p>
</div>

5 Comments

So if I put it here, this should work? } else if (result[i] != zip) { alert("No Match1"); console.log(zip + " is != to " + result[i]); break;
@DallasClymer If you put break in the loop, the control will be thrown outside of for and the rest of the code will be executed
While we are at the pattern attribute, the if (zip.length.. could also be replaced by the required attribute.
@Abhitalks In JS? required will only check for the any value, here OP want to have a 5-digits, so added it.
Oh yes @Tushar. My bad, overlooked that.
1

Put break in the condition branch body

function getZip(e){
e.preventDefault();
var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
var result = ["48650","48611","48746","48614","48706"];

  for (var i=0; i<result.length; i++){
    //console.log(result[i]);

      //if (zip.length == 5 && zip == result[i]){
        if (zip == result[i]){
          console.log(zip + " is = to " + result[i]);
          alert('Match ' + zip);
          break;

        } else if (result[i] != zip) {
        alert("No Match1");
        console.log(zip + " is != to " + result[i]);
          break;

        } else {
        alert("No Match2");
        console.log(zip + " is != to " + result[i]);
          break;
      }
        //return false;
  }
  if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
    alert('Please enter a zip code!');

  } else if (zip.length > 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (zip.length < 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (isNaN(zip))  { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
    alert("Please enter a numeric value.");
  }
}
<div class="searchZip">
  <p>Please enter your zip code for availability</p>
     <form>
        <input type="text" name="zip" id="zip" placeholder="Zip Code">
           <button onclick="getZip(event);">Check</button>
     </form>
     <p id="display"></p>
</div>

1 Comment

The breaks only work to show the first match in the array, and the rest show as false becasue it's not looping through the rest.
1

The algorithm can be even easier

function getZip(e){
e.preventDefault();
var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form.
var result = ["48650","48611","48746","48614","48706"];

        if (result.indexOf(zip) === -1){
          alert("No Match1");
        } else {
          alert('Match ' + zip);
        }
   
  if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message.
    alert('Please enter a zip code!');

  } else if (zip.length > 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (zip.length < 5) {
    alert("Please enter a valid 5 digit numeric zip code.");

  } else if (isNaN(zip))  { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
    alert("Please enter a numeric value.");
  }
}
<div class="searchZip">
  <p>Please enter your zip code for availability</p>
     <form>
        <input type="text" name="zip" id="zip" placeholder="Zip Code">
           <button onclick="getZip(event);">Check</button>
     </form>
     <p id="display"></p>
</div>

2 Comments

This did simply it, may I ask what the if (result.indexOf(zip) === -1){ means?
indexOf returns index of the value in the array. It returns -1, if the value is not found.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.