提问人:Shaz 提问时间:9/22/2023 最后编辑:Shaz 更新时间:9/22/2023 访问量:27
使用 JavaScript 验证两个搜索框的输入
Use JavaScript to validate input for the two search boxes
问:
我只想使用 js 进行验证。名称框应接受不超过 20 个字符,并且不接受数字。货币代码框应只接受三个大写字母 A-Z。每个框的搜索按钮应显示一条弹出消息,其中包含所有匹配项的国家/地区名称和货币(最多 5 个)
我试着让国家成为关键,货币是价值 我只需要打印出键名称和该键的值,并使用事件侦听器来验证/显示结果和错误输入的警报功能。 到目前为止没有任何工作,我不确定我是否以错误的方式做,或者是否是另一个错误。 这是我搜索框的html代码:
<div class="search-box">
<label for="name">Search:</label>
<input type="text" id="name" name="name" placeholder="Enter name">
<button id="name-search-button" type="submit">Search</button>
</div>
<!-- Second Search Box: Search by Currency -->
<div class="search-box">
<input type="text" id="currency" name="currency" placeholder="Enter code">
<button id="currency-search-button" type="submit">Search</button>
</div>
这是我的js代码
var countriesData = {
"Afghanistan": "AFN",
"Brazil": "BRL",
"Canada":"CAD",
"Germany":"EUR",
"Libya": "LYD",
"Mexico": "MXN",
"Morocco": "MAD",
"Pakistan": "PKR",
"Romania": "RON",
"Spain": "EUR",
"Zambia": "ZMK",
"Zimbabwe": "ZWD",
"Sudan": "SDG",
"Serbia": "RSD",
"Samoa": "EUR",
"Portugal": "EUR",
"Saudi Arabia": "SAR",
"Somalia": "SOS",
"Philippines": "PHP",
"Norway": "NOK"
};
function performSearch(inputElement, resultsElement) {
const searchValue = inputElement.value.trim();
const results = [];
// Validate and search for matches based on the inputElement's ID
if (inputElement.id === "name") {
// Validate: No more than 20 characters and no numbers
if (searchValue.length <= 20 && !/\d/.test(searchValue)) {
for (const country in countriesData) {
if (country.toLowerCase().includes(searchValue.toLowerCase())) {
results.push({ name: country, currency: countriesData[country] });
if (results.length >= 5) break; // Limit to 5 results
}
}
}
} else if (inputElement.id === "currency") {
// Validate: Three upper case letters A-Z
if (/^[A-Z]{3}$/.test(searchValue)) {
for (const country in countriesData) {
if (countriesData[country] === searchValue) {
results.push({ name: country, currency: searchValue });
if (results.length >= 5) break; // Limit to 5 results
}
}
}
}
// Display the results
resultsElement.textContent = ""; // Clear previous results
results.forEach(result => {
const resultItem = document.createElement("p");
resultItem.textContent = `${result.name} - Currency: ${result.currency}`;
resultsElement.appendChild(resultItem);
});
}
// Event listeners for search buttons
document.getElementById("name-search-button").addEventListener("click", () => {
const nameInput = document.getElementById("name");
const resultsElement = document.getElementById("name-results");
performSearch(nameInput, resultsElement);
});
document.getElementById("currency-search-button").addEventListener("click", () => {
const currencyInput = document.getElementById("currency");
const resultsElement = document.getElementById("currency-results");
performSearch(currencyInput, resultsElement);
});
答: 暂无答案
评论