简体   繁体   中英

Storing Key and Value using Javascript in array

I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array.

I have tried this by creating a method but it is not working perfectly can you please help me..

function addCheckboxVAlues(checked){
    var split = checked.value.split("|");
    var key =split[0];
    var value=split[1];
    var chks = $("input[name='"+key+"']:checked");
      if (chks.length > 0)  {
         uninvoiced.push(value);
      } else {
         uninvoiced.pop(key);
      }
      console.log(uninvoiced);
}

You need to use splice to remove the element from the array

function addCheckboxVAlues(checked){
    var split = checked.value.split("|");
    var key =split[0];
    var value=split[1];
    var chks = $("input[name='"+key+"']:checked");
    var index = uninvoiced.indexOf(key);
      if (chks.length > 0)  {
         uninvoiced.push(value);
      } else if(index > -1){
         uninvoiced.splice(index, 1);
      }
      console.log(uninvoiced);
}

This code looks way more complex than it needs to be. Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this . All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked.

That will be hugely more efficient than running a checked selector every time.

The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way.

 var uninvoiced = []; function addCheckbox(el) { var value = el.value.split('|')[1]; if (el.checked) { uninvoiced.push(value); } else { uninvoiced.splice(uninvoiced.indexOf(value), 1); } console.log(uninvoiced); } 
 foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)"> fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)"> 

There is a polyfill for indexOf on MDN .

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