Hi everyone! I've been working/struggling with this issue for quite some time and would really appreciate any help I can get.
Basically, I have 5 text input questions (exp: "MO01_01") in my questionnaire that are randomly selected for each participant. In these 5 questions participants are asked to write down numbers (exp: 100) and are immediately given some feedback, using a javascript code, on what the sum of those numbers are. Below is the code I've written that works, however in this code the ID's for the 5 text input questions are fixed (i.e., "MO01_01", "MO02_01", "MO03_01", "MO04_01", "MO05_01"). What I need instead is to be able to dynamically change the ID based on a php code that I use earlier to randomly select the text input questions.
Here's the php code where I randomly choose which questions to display:
if (!isset($mo_set)) {
$mo_set = array('MO0'.$number[0], 'MO0'.$number[1], 'MO0'.$number[2], 'MO0'.$number[3], 'MO0.$number[4]);
shuffle($mo_set);
registerVariable($mo_set);
put('SN01_01', $mo_set[0]);
put('SN01_02', $mo_set[1]);
put('SN01_03', $mo_set[2]);
put('SN01_04', $mo_set[3]);
put('SN01_05', $mo_set[4]);
}
question($mo_set[0]);
question($mo_set[1]);
question($mo_set[2]);
question($mo_set[3]);
question($mo_set[4]);
And here's the code where I am trying to give feedback on the sum of the numbers entered into the 5 text input questions:
<div id="info01"> - </div>
<script type="text/javascript">
function calculateSum() {
var MO01_01_value = parseFloat(document.getElementById("MO01_01").value);
var MO02_01_value = parseFloat(document.getElementById("MO02_01").value);
var MO03_01_value = parseFloat(document.getElementById("MO03_01").value);
var MO04_01_value = parseFloat(document.getElementById("MO04_01").value);
var sum = 0;
if (!isNaN(MO01_01_value)) {
sum += MO01_01_value;
}
if (!isNaN(MO02_01_value)) {
sum += MO02_01_value;
}
if (!isNaN(MO03_01_value)) {
sum += MO03_01_value;
}
if (!isNaN(MO04_01_value)) {
sum += MO04_01_value;
}
var remainingMoney = Math.round(300 - sum);
document.getElementById("info01").innerHTML = remainingMoney + " cents";
}
var inputs = document.querySelectorAll('input[id^="MO"]');
inputs.forEach(function(input) {
input.addEventListener("input", calculateSum);
});
</script>
As I said, the question ID's here in this java code (exp: "MO01_01") should match the question ID's that are randomly selected in the php above ($mo_set[0] for example which might be MO07 for a specific participant). Any ideas on how I can fix this code?