lundi 19 avril 2021

How to change array value in javascript through functions? [duplicate]

I am unable to figure out how to change the array value based on what the user chooses. Please tell me what mistake have I done and how to correct it?

Expectation : I am trying to push the value of checkboxes that is checked by users into arrayop array. Let's say user checks "addition" then arrayop which is currently equal to ["?"] should become arrayop = ["?", "+"]; Then after arrayop gets updated based on user selection then if "display checked values" button is clicked then it should randomly choose any value from the current updated arrayop array and display it on screen. Suppose "+" was choosen randomly then it should get displayed.

Problem occurring : The problem is arrayop doesn't get updated in the function that gets called when "display checked values" button is clicked! I am new to javascript and not able to understand how can I achieve what I am trying to do? The code is shown below:

CODE

var arrayop = ["?"];

function formsubmit() {
  arrayop = [];
  var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked');
  for (var checkbox of markedCheckbox) {
    arrayop.push(checkbox.value);
  }
  console.log("Inside formsubmit & arrayop =", arrayop);
}

function display() {
  console.log("Inside display & arrayop =", arrayop);
  var symbol = arrayop[Math.floor(Math.random() * arrayop.length)];
  document.body.append(symbol);
}
<body>
  <form action="">
    <label>Select an option</label>
    <br>
    <input type="checkbox" id="additionCheckbox" name="additionCheckbox" value="+">
    <label for="additionCheckbox"> Addition</label>
    <input type="checkbox" id="subtractionCheckbox" name="subtractionCheckbox" value="-">
    <label for="subtractionCheckbox"> Subtraction</label>
    <br/>
    <button onclick="formsubmit()">Submit form</button>
  </form>
  <br/>
  <button onclick="display()" class="btn">Display Checked values</button>
  <script src="testScript.js"></script>
</body>



Aucun commentaire:

Enregistrer un commentaire