I have a web form that takes the input when a user enters a weight, and I need the kennel size to display according to the weight, right now it only shows "mini" as the page refreshes but never changes.
I think I need another event handler for each time a weight is entered but I’m not quite sure how to do that..
this is what I have written in javascript:
window.addEventListener("load", getKennelSize);
var petForm = document.getElementsByTagName("form");
var petSize;
function getKennelSize() {
var petWeight = document.getElementById("weight").value;
if (petWeight === NaN) {
petSize = " ";
} else if (petWeight <= 4) {
petSize = "mini";
} else if (petWeight >= 4 && petWeight <= 12) {
petSize = "small";
} else if (petWeight > 12 && petWeight <= 50) {
petSize = "medium";
} else {
petWeight > 50;
petSize = "large";
}
document.getElementById("size").value = petSize;
}
document.getElementById("size").value = petSize;
And the elements I’m trying to target in the HTML web form are:
<p>
<label for="weight">Weight of pet?</label>
<input type="text" name="weight" id="weight" class="quantity" />
<label for="size">Kennel size</label>
<input type="text" name="size" id="size" class="cost" readonly>
</p>
2
Answers
Comments
What you are probably looking for is a change or input event on the weight input. Also I would change your weight input to a type of number instead of string.
HTML
JS
The load event is fired only once when the whole page has loaded. ["load" event doc]
To run getKennelSize function each time the weight changes, replace
with
also, it seems that
getKennelSize
is a function which calculates and updatessize
value in the html form, so it would be a good practice to name the functionupdateKennelSize
.