I am using the following script on a form with multiple results to automatically enter a mark based on the percentage scored in a test. The scripts works fine but only if the input box and the output box are adjacent. I need to lay the score sheet out in a table - or divs but whenever I separate the inputs & outputs by placing them in table cells, the script breaks down. I need the function to work on over thirty pairs of text inputs. Any help appreciated.
<td>
<input type="number" name="mod1a_s" class="input_select_teala_ltxt" id="mod1a_s" value="<?php echo $foo ?>" min="0" max="100" oninput="updateInputBox2(this)"/>
</td>
<td><input type="number" name="mod1_s" class="input_select_teal_ltxt" id="mod1_s" max="3" min="0" step="1" value="<?php echo $foo ?>" /></td>
<script>
function updateInputBox2(inputBox) {
// Get the value from the current input box
var inputValue = parseFloat(inputBox.value);
// Find the corresponding output box
var outputBox = inputBox.nextElementSibling;
// Check the range and update the output box accordingly
var outputBoxValue;
if (inputValue >= 90) {
outputBoxValue = 3;
} else if (inputValue >= 80 && inputValue <= 89) {
outputBoxValue = 2;
} else if (inputValue >= 70 && inputValue <= 79) {
outputBoxValue = 1;
} else {
outputBoxValue = 0;
}
// Update the value in the corresponding output box
outputBox.value = outputBoxValue;
}
</script>
I would like to adapt the function further so that it can be used with tables or other layout objects. I have tried rewriting the code in various ways but with no success. I am sure I am missing something obvious!
You can use
getElementById()orquerySelector()to find needed element (output). This will let you position your element wherever you want it.