简体   繁体   中英

javascript deleting the array of elements

i am having 10 check boxes.if i click the value of the check box has to push to the array,if i unchecked the check box then the corresponding check box value has to be deleted from the array? pls...anyone give reply for this

Does this have to work exactly like this? It would be easier to generate an array of values from the checked checkboxes when needed.

Something like:

// Pass reference to a parent element of all checkboxes, for example the form
function getCheckedBoxes(parent) {
  var result = [];
  var inputs = parent.getElementsByTagName("input");
  for (var i = 0, len = inputs.length; i < len; i++) {
    var cb = inputs[i];
    if (cb.type.toLowerCase() === "checkbox" && cb.checked)
      result.push(cb.value);
  }
  return result;
}

Use array.splice(index,howmany,element1,.....,elementX) . See more about splice here: http://www.w3schools.com/jsref/jsref_splice.asp .

try javascript associative array like:

a['title'] = 'Mr.'; 
a["fname'] = 'Brad'; 
a['lname'] = 'Johnson'; 
delete a['title'];

Its simple... when user checks it adds with its id as key and when unchecks it deletes

function getChecked(ename)
{
field = document.getElementsByName(ename);
var topub = new Array();
for (i = 0; i < field.length; i++)
    if(field[i].checked == true)
    {
        topub.push(field[i].id);
    }
    return topub;
}

Above is what i used in such cases. i keep name of all checkboxes same and then pass name to this function and it returns array. So you can replace ur array with returned one. Like :

var yourOldArray = new Array();<br>
yourOldArray = getChecked("name attribute of checkboxes");

All you need to make sure is all checkboxes have same value for their name attribute.

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