hego64 hego64 -4 years ago 58
Javascript Question

Make selections from multiple drop-downs update when criteria is met

I feel like this question is very vague, and I apologize because I can't seem to come up with a better name.

Ahem. As for the actual question. I've got two drop-down menus, and I'd like to make it so that whenever I have the correct value in each one, ex.

Level 1
and
Barbarian
, it updates the connected fields. This works just fine with what I have here, but the problem is, if I leave
Barbarian
how it is and change the level to
Level 2
, it won't update the connected fields until
Barbarian
has been switched to something else and then put back on
Barbarian
. How can I make it update right when the fields are the correct for a certain setup? I'm assuming some sort of listener, but I really don't know all that much about Javascript, as I'm new to it all.

function classDefine(){
var playerClass = document.getElementById('class').value;
var playerLevel = document.getElementById('level').value;
if (playerClass == "Barbarian" && playerLevel == "Level 1") {
document.getElementById("fort").value = 2;
document.getElementById("ref").value = 2;
document.getElementById("will").value = 2;
document.getElementById("baseAttackBonus").value = 2;
}
else if (playerClass == "Barbarian" && playerLevel == "Level 2"){
document.getElementById("fort").value = 5;
document.getElementById("ref").value = 5;
document.getElementById("will").value = 5;
document.getElementById("baseAttackBonus").value = 5;
}
}

Answer Source

You can use the onChange listener on each of the select boxes to run the function whenever either of them changes.

<select id="class" onChange="classDefine()">
    <option>...</option>
</select>

or in javascript

document.getElementById('class').addEventListener("change", classDefine);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download