After creating a JavaScript array and implementing a search input field box to find matching results, I encountered an issue with the form validation code. It appears that the validation script is being ignored or overridden by the rest of the script.
The problem arises when the input box is left empty and submitted, resulting in a wrong match with no value enclosed within single quotes.
To address this issue, I aim to develop a validation script that first checks if the input box is blank. If it is, the user should be notified that input is required. On the other hand, if the input box is not blank, the remainder of the script should function as intended.
Do you have any suggestions on how to fix this?
Below is the code I currently have:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Test Search Page</title>
</head>
<body>
<form method="get" action="input" onsubmit="return validate();">
<fieldset>
<input id="formInput" name="formInput" type="text" placeholder="Type Code Number Here" required/>
</fieldset>
</form>
<input id="searchBtn" type="submit" value="Submit">
</body>
</html>
SCRIPT
var data = [{
code: "2222",
value: "$10.00"
}, {
code: "3333",
value: "$30.00"
}, {
code: "4444",
value: "$50.00"
}, {
code: "5555",
value: "$100.00"
}, {
code: "1111",
value: "$300.00"
}, {
code: "7777",
value: "$500.00"
}, {
code: "8888",
value: "$1,000.00"
}, {
code: "9999",
value: "$3,000.00"
} ];
//Script for validating an empty input box
function validate()
{
var ch = document.getElementById('formInput');
if(ch.value === '')
{
alert('You Must Enter A Code Number First.');
return false;
}
}
//Script for searching array for a match
document.getElementById("searchBtn").addEventListener('click', function() {
var formInput = document.getElementById("formInput").value,
foundItem = null;
for (i = 0; i < data.length; i++) {
if (data[i].code == formInput) {
foundItem = data[i];
break;
}
}
if (foundItem) {
alert("Jewellery Code # '" + foundItem.code + "' Value: " + foundItem.value);
} else {
alert("Code Number: '" + formInput + "' Was Not Found");
}
});