I recently received a 'good, but not good enough' rating on a coding exercise I was asked to perform. It was to validate that if "Product complaint" option was selected that Product name, Product size, Use-by date and Batch code fields all needed to have values. What can I do to improve the JS to go from 'good, but not good enough' to 'great'?
JS:
document.querySelector("form").addEventListener("submit", function(e) {
var enquiryType = document.querySelector("#enquirytype");
if (enquiryType.value === "pc") {
validateProductDetails();
e.preventDefault();
}
});
function validateProductDetails() {
var requiredFields = document.querySelectorAll('[id^="product-"]'),
requiredLabel = document.querySelectorAll('[for^="product-"]'),
formSubmit = document.forms[0],
requiredIsEmpty = [],
i;
for (i = 0; i < requiredFields.length; i += 1) {
if (requiredFields[i].value.length === 0) {
alert('Please enter the ' + requiredLabel[i].innerHTML + ".");
requiredFields[i].focus();
requiredIsEmpty.push(requiredFields[i]);
return false;
}
}
if (requiredIsEmpty.length === 0) {
formSubmit.submit();
return true;
}
}
HTML:
<form action="/" method="get">
<label for="enquirytype">Enquiry type</label>
<select name="enquiry" id="enquirytype" required>
<option value="">Choose</option>
<option value="ge">General enquiry</option>
<option value="pf">Product feedback or enquiry</option>
<option value="pc">Product complaint</option>
</select>
<label for="product-name">Product name</label>
<input type="text" id="product-name">
<label for="product-size">Product size</label>
<input type="text" id="product-size">
<label for="product-use-by">Use-by date</label>
<input type="text" id="product-use-by">
<label for="product-batch">Batch code</label>
<input type="text" id="product-batch">
<input type="submit" value="Submit" id="form-submit">
</form>