Jon Watson Jon Watson - 1 month ago 6
Javascript Question

Using JavaScript to load checkbox Values into a string

What I want visitors to be able to do is: tick any number of checkboxes for products they'd like to enquire about, and have a link appear at the bottom of the page after they've ticked the first. They click the link and it autofills a form.

I've got the latter part sussed using a query, but I need to get comma separated checkbox values and feed them into a string for use in my link - i.e. if my checkbox code is:



<input type="checkbox" id="selected" name="selected" value="Blue" class="products"><br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"><br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products">





I need the string generated by JS to be: http://example.com/?subject=Products&checked=Blue,Green,Purple

I've tried adapting this code (found here: Best way to get all selected checkboxes VALUES in jQuery), without success:



var checkedValues = $('.products:checkbox:checked').map(function() {
return this.value;
}).get();





How can I load my checkbox values into the query string I need?

Answer

It looks like the below produces the string.

$("button").on("click", function(){
	var arr = []
	$(":checkbox").each(function(){
	   if($(this).is(":checked")){
		 arr.push($(this).val())
	   }
	})
	var vals = arr.join(",")
	var str = "http://example.com/?subject=Products&" + vals
	console.log(str)	
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" id="selected" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products"> Purple
<br>
<button>button</button>