Ordering an array by the order in which checkboxes were checked

Hi all,

I have this bit of code;

	var checkboxes = document.getElementsByName("filter_option[]");
	var queryString = [];
	for(var i=0;i<checkboxes.length;i++) {
		if( checkboxes[i].checked ) {
			queryString.push( checkboxes[i].value );
		}
		
	}

Open in new window


Which scans through a load of checkboxes and adds them to an array (push method).

Now, I'm looking to ammend the code to add the checked values to the array in the order they were clicked - could anyone help me do this?

Cheers
dolythgoeAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
leakim971Connect With a Mentor PluritechnicianCommented:
For example : http://jsfiddle.net/94Epj/2/


var queryString = [];
window.onload = function() {
    var checkboxes = document.getElementsByName("filter_option[]");
    for(var i=0;i<checkboxes.length;i++) {
        checkboxes[i].onchange = function() {
            if(this.checked) {
                queryString.push(this.value);
            }
            else {
                queryString.splice(queryString.indexOf(this.value),1);
            }
            alert(queryString.toString()); // REMOVE THIS LINE!!!
        }
    }
}

Open in new window

0
 
dolythgoeAuthor Commented:
Oh and remove them if they were unchecked - so it keeps a record of the checking history in the array if you like.. newest added to the back..might be an onclick function? That's ok..
0
 
dolythgoeAuthor Commented:
Awesome thanks!

I pastd it in but recevied this error:

queryString.push is not a function? Strange as this worked in it's previous form and it works in your example..

In my code this sits within a function:

function ajaxRequest() {

//blah

	var checkboxes = document.getElementsByName("filter_option[]");
	var queryString = [];
    for(var i=0;i<checkboxes.length;i++) {
        checkboxes[i].onchange = function() {
            if(this.checked) {
                queryString.push(this.value);
            }
            else {
                queryString.splice(queryString.indexOf(this.value),1);
            }
        }
    }

}

Open in new window


Is something occuring with the onchange event within a function? (ajaxRequest gets called on every checkbox click)
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
leakim971PluritechnicianCommented:
please provide aink to your page
0
 
dolythgoeAuthor Commented:
It's not online but here's the code:

function ajaxFunction(){
	var ajaxRequest; 
	
	//Show loading graphic
	document.getElementById('loading').style.display="block";
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("A problem has occured with your request");
				return false;
			}
		}
	}
	
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
			if(ajaxRequest.readyState == 4){
			document.getElementById('loading').style.display="none";
			document.getElementById('search_results').innerHTML = ajaxRequest.responseText;
			
			
		}
	}
	
	//Need to grab query string and append checked checkboxes array
	var checkboxes = document.getElementsByName("filter_option[]");
	var queryString = [];
    for(var i=0;i<checkboxes.length;i++) {
    
	checkboxes[i].onchange = function() {
            if(this.checked) {
                queryString.push(this.value);
            }
            else {
                queryString.splice(queryString.indexOf(this.value),1);
            }
		}
        
    }
	
	prevQS="<?php echo($_SERVER["QUERY_STRING"])?>";
	queryString = "?"+prevQS+"&filter_options=" + queryString.join(",");
	ajaxRequest.open("GET", "filter_query.php" + queryString, true);
	ajaxRequest.send(null);
	//Call disable filter function
	$.disableFilter(queryString);
}

Open in new window


Called from checkboxes e.g:

<input type="checkbox" onClick="ajaxFunction(); addToFilterBoard();" name="filter_option[]" value="28-515" id="chk515"  />

Open in new window

0
 
leakim971PluritechnicianCommented:
the code provided will not work inside your function
don't modify it
use queryString anywhere you need it in your code, it's not a problem
0
 
dolythgoeAuthor Commented:
I'm not sure I follow? Do you mean take your code outside of this function? Keep queryString global?
0
 
leakim971PluritechnicianCommented:
yes, queryString global
0
 
dolythgoeAuthor Commented:
I took the code as you wrote it - so I have the below but getting the error still:

Error: queryString.join is not a function

<script type="text/javascript">
<!-- 
//Browser Support Code
var queryString = [];
window.onload = function() {
    var checkboxes = document.getElementsByName("filter_option[]");
    for(var i=0;i<checkboxes.length;i++) {
        checkboxes[i].onchange = function() {
            if(this.checked) {
                queryString.push(this.value);
            }
            else {
                queryString.splice(queryString.indexOf(this.value),1);
            }
  
        }
    }
}

function ajaxFunction(){
	var ajaxRequest; 
	
	//Show loading graphic
	document.getElementById('loading').style.display="block";
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("A problem has occured with your request");
				return false;
			}
		}
	}
	
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
			if(ajaxRequest.readyState == 4){
			document.getElementById('loading').style.display="none";
			document.getElementById('search_results').innerHTML = ajaxRequest.responseText;
			
			
		}
	}
	

	prevQS="";
	queryString = "?"+prevQS+"&filter_options=" + queryString.join(",");
	ajaxRequest.open("GET", "filter_query.php" + queryString, true);
	ajaxRequest.send(null);
	//Call disable filter function
	$.disableFilter(queryString);
}


//-->
</script>

Open in new window

0
 
leakim971PluritechnicianCommented:
replace 56 and 57 by :

      somethingelse = "?"+prevQS+"&filter_options=" + queryString.join(",");
      ajaxRequest.open("GET", "filter_query.php" + somethingelse, true);
0
 
dolythgoeAuthor Commented:
Same issue :(
0
 
leakim971PluritechnicianCommented:
<< same >>?
0
 
leakim971PluritechnicianCommented:
ok, modify line 60 to :

$.disableFilter(somethingelse);
0
 
dolythgoeAuthor Commented:
That seemed to work but the results are a little odd.

I think because if it's already in the array and called again it adds the same value. How would I check for this?

I don't mind converting the whole function to jquery since that has the inarray function.

Cheers
0
 
leakim971PluritechnicianCommented:
>I think because if it's already in the array and called again it adds the same value. How would I check for this?

it work fine on the test page, you don't have this issue
0
 
dolythgoeAuthor Commented:
Ok, something else is happening - so let me try and understand what your code is doing.

- Detecting onchange events with the checkbox array and updating the querystring array?

I then re-use querystring arr in the ajaxFunction() which is also called from checking a box.

So the potential issue here is that the onchange event is happening AFTER the ajaxfunction() call...

Could I wrap these up into the same function (ajaxfunction())?
0
 
leakim971PluritechnicianCommented:
>Could I wrap these up into the same function (ajaxfunction())?

you can put it inside the onchange (don't forget to remove the onclick):


checkboxes[i].onchange = function() {
            if(this.checked) {
                queryString.push(this.value);
            }
            else {
                queryString.splice(queryString.indexOf(this.value),1);
            }
ajaxfunction(); // <-------------------------- HERE
        }

Open in new window

0
 
dolythgoeAuthor Commented:
Thanks for all your help :)
0
All Courses

From novice to tech pro — start learning today.