Jump to content

Help with Javascript splice


Err

Recommended Posts

hey guys. I need some help.I'm working on a script where it randomizes an array of elements that are checked. I'm using input boxes, and depending on what which input box is checked, is the array that gets randomized. For example purposes, I shortened my script to the problem area.This is what I'm doing: I have 12 input boxes (checkboxes) and an array called "a" with numbers 0 - 11 set in it. I then use a FOR loop to loop through all the input boxes and check, with an IF condition, which ones are NOT checked. I imagine that if I use a.splice(j, 1) (where "j" is the FOR variable) it should take the current number of "j" and remove it from the array.That's as far as I've got. The "a" array messes up after the splice, it displays numbers which should not be checked. Now, it could be just me, and I may have messed up the splice function in some way or have coded this in a way where this can't be done... ?You can find a working example here: http://oneuse.awardspace.com/test/test_h1.htmlEdit: Made a minor change in code so text will reset after every button press.Thanks for any help on this matter. :)

Link to comment
Share on other sites

Part of the problem may be that you are splicing the array inside of that loop. If your array has 12 elements, and three checkboxes are checked (#0, #4, and #6) and then you loop through that array, at j = 0, you'll splice out the first element in the array so that the array now has 11 elements. When you get to j = 4, you'll splice out the fourth element in that (smaller) spliced array. This would actually be the fifth element from the original array.You might consider ditching the splice and use push to create a new array.

  function randomize() {	var reset_txt = document.getElementById('r_txt').innerHTML;	if (reset_txt != null) {	  document.getElementById('r_txt').innerHTML = "";	}	var a = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);	var checked = new Array();	document.getElementById('r_txt').innerHTML+=("<br \/> a: " +a+ "<br \/>");	for (var j = 0; j < 12; j++) {	  if (document.getElementById('chk')[j].checked == false) {		document.getElementById('r_txt').innerHTML+=("<br \/>" +j+ " " +document.getElementById('chk')[j].checked)		checked.push(j);	  }	}	document.getElementById('r_txt').innerHTML+=("<br \/><br \/> checked a: " +checked);  }

Link to comment
Share on other sites

Awesome! Thanks for the reply. It was a huge help. I had to change the code a little bit, but it works. You can see a working example on the same link.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...