首页 > 解决方案 > 如果数组中的值匹配,则检查搜索输入并显示响应

问题描述

首先,我真的是 Javascript 的新手,最近几周才刚刚开始。

我想要的是:

一个搜索栏,用户可以在其中键入他们的邮政编码,然后脚本通过数组搜索以查看邮政编号是否在任一对象中 - 然后响应在它所在的对象中找到的消息。

我得到它来回复消息 - 但仅限于第一个邮政编号。我想问题出在循环内。

var montering = {
  "postnummer": [{
    "id": "0",
    "codes": ["3089", "2089"],
    "msg": "Message 1"
  }, {
    "id": "1",
    "codes": ["3088", "2088"],
    "msg": "Message 2"
  }]
}



var placeholder = "";
document.getElementById('melding').innerHTML = placeholder;

//Script to search array for a match 
document.getElementById("searchBtn").addEventListener('click', function() {
  var formInput = document.getElementById("formInput").value,
    foundItem = null; //we'll store the matching value here

  if (formInput === '') {
    alert('Tast inn et postnummer');
    return false;
  }

  for (i = 0; i < montering.postnummer.length; i++) {
    if (montering.postnummer[i].codes[i] == formInput) {
      foundItem = montering.postnummer[i].codes[i];
      break; //we've found a match, no sense to continue
    }
  }

  if (foundItem) {
    var msg = document.getElementById('melding');
    melding.innerHTML += 'Melding: ' + montering.postnummer[i].msg;
  } else {
    alert("Code Number: '" + formInput + "' Was Not Found");
  }

});
<form method="get" action="input">
  <fieldset>
    <input id="formInput" name="formInput" type="text" placeholder="Tast inn postnummeret ditt" required/>
  </fieldset>
</form>

<input id="searchBtn" type="submit" value="Finn pris">
<p id="melding">Placeholder</p>

标签: javascriptarraysloops

解决方案


用于:Array.prototype.includes_codes

var montering = {
  "postnummer": [{
    "id": "0",
    "codes": ["3089", "2089"],
    "msg": "Message 1"
  }, {
    "id": "1",
    "codes": ["3088", "2088"],
    "msg": "Message 2"
  }]
}



var placeholder = "";
document.getElementById('melding').innerHTML = placeholder;

//Script to search array for a match 
document.getElementById("searchBtn").addEventListener('click', function() {
  var formInput = document.getElementById("formInput").value,
    foundItem = null; //we'll store the matching value here

  if (formInput === '') {
    alert('Tast inn et postnummer');
    return false;
  }

  for (i = 0; i < montering.postnummer.length; i++) {
    if (montering.postnummer[i].codes.includes(formInput)) {   // change this line
      foundItem = montering.postnummer[i].codes[i];
      break; //we've found a match, no sense to continue
    }
  }

  if (foundItem) {
    var msg = document.getElementById('melding');
    melding.innerHTML += 'Melding: ' + montering.postnummer[i].msg;
  } else {
    alert("Code Number: '" + formInput + "' Was Not Found");
  }

});
<form method="get" action="input">
  <fieldset>
    <input id="formInput" name="formInput" type="text" placeholder="Tast inn postnummeret ditt" required/>
  </fieldset>
</form>

<input id="searchBtn" type="submit" value="Finn pris">
<p id="melding">Placeholder</p>


推荐阅读