简体   繁体   中英

How to pass a value from one function to another

 var boxes = document.getElementsByName('toggle'); function markPreceding() { var curIndex = null; for (var j = 0; j < boxes.length; j++) { if (boxes[j].checked) { curIndex = j; } } } function checkInputs() { for (var k = 0; k <= curIndex.length; k++) { boxes[k].checked = true; } } for (var i = 0; i <= boxes.length; i++) { boxes[i].onchange = markPreceding; boxes[i].onchange = checkInputs; }
 <input type="checkbox" id="product-1" name="toggle"> <input type="checkbox" id="product-2" name="toggle"> <input type="checkbox" id="product-3" name="toggle"> <input type="checkbox" id="product-4" name="toggle"> <input type="checkbox" id="product-5" name="toggle">

Have a problem passing this "curIndex" value to checkInputs function. This should check inputs before checked input and get its value to do it.

Only ES5 synthax needed for this project.

EDIT: The ES5 Syntax way

const boxes = document.getElementsByName('toggle');

boxes.forEach(function(box, I) {
  box.onclick = function(e) {
    markPreceding(i);
  };
});

function markPreceding(i) {
  for (var j = 0; j < boxes.length; j++) {
    if(j <= i) {
      document.getElementById('product-' + (j + 1)).checked = true;
    } else {
      document.getElementById('product-' + (j + 1)).checked = false;
    }
  }
}

ORIGINAL:

Try using this:

const boxes = document.getElementsByName('toggle');

boxes.forEach((box, i) => {
  box.onclick = (e) => {
    markPreceding(i);
  };
});

function markPreceding(i) {
  for (var j = 0; j < boxes.length; j++) {
    if(j <= i) {
      document.getElementById(`product-${j + 1}`).checked = true;
    } else {
      document.getElementById(`product-${j + 1}`).checked = false;
    }
  }
}

For some reason, there seems to be an issue with updating the inputs through the NodeList array returned by document.getElementsByName . Not sure why, but this code has been verified. See working example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM