1

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?

5
  • Are you actually using jQuery or not ? Commented Oct 12, 2016 at 20:27
  • Try with var checkedValues = $('.products:checkbox:checked').map(function() { return $(this).attr('value'); }); Commented Oct 12, 2016 at 20:30
  • Hey @Robiseb - I'm not sure what you mean... From the various examples I've, code similar to the above usually gets the required results, I'm just having trouble adapting it for my specific use. See [link] (jquery-howto.blogspot.co.uk/2013/02/…) or [link] (tutorialrepublic.com/faq/…) Commented Oct 12, 2016 at 20:34
  • 1
    jQuery is a famous JavaScript library, it can helps you to write more easily some javascript functions / actions /... but in your case, I prefer advice you to learn pure JS. So check Rob M.'s first part answer. Commented Oct 12, 2016 at 20:44
  • Aaah, I'm with you now. I'm happy using whatever, but don't fully understand either. I've only really had training in HTML, CSS and PHP, so getting my head around either JavaScript or jQuery is a bit of a challenge. Thanks for your help :) Commented Oct 12, 2016 at 20:51

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

5 Comments

This is great! But is it possible for the values to load dynamically on ticking the checkbox, rather than via a button. And is it then possible for the button to be replaced with the generated link?
you could set values dynamically. I'm not sure if that is what you want. I chose to show you a button to simulate how to get all the values of the checked check boxes after an event like when you submit a form. I don't know why you would want to change the value after clicking on the checkbox . oh maybe you want to look into .change() stackoverflow.com/a/7031408/1893672. That does something after you click a checkbox
Thanks for that! What I'm trying to do is generate a link when the checkboxes on the following page are clicked: [link] (kittahbirmans.co.uk/kittens) The link will appear once the first box is checked and the value should change dynamically based on the boxes selected. When the link is clicked (as per var str above) it takes them to a form, which pre-populates with the data from the checkbox values. I can't have the form on the same page. The button idea might work if I can set it based on the selected fields, but ideally it'd be a dynamic link.
It sound like you literally want to create an a tag that has the href updated each time the user clicks on a checkbox. you need to use .change() . Every time the user clicks the checkbox .change will activate and you will be able to test if the user has clicked on the checkbox. and so you will be able to update the a tag. which is kind of like another question. look for example for .change() on jquery and have fun.
Awesome advice! I can't deny that you've answered the title of this question! I may ask another one more closely related to the link idea :) Thanks!
1

Get your string of values like this

var checked = Array.prototype.slice.call(document.querySelectorAll('.products:checked')).map(function(el){
  return el.value;
}).join(',');

Then create a <a> element

var aEl = document.createElement("a");
aEl.setAttribute("href", "http://example.com/?subject=Products&checked=" + checked);

And place it where you want (for this exemple, at the end of the body)

document.body.appendChild = aEl;

Or in an empty and existent <div>

// HTML
<div id="myEmptyDiv"></div>
// JS
document.getElementById('myEmptyDiv').innerHTML = aEl;

Here a Fiddle with all those things and a change listener

1 Comment

Awesome! Another noob question... How do I use that console.log value to actually retrieve the values in the form of my string? What I need to do is use console.log('example.com/?subject=Products&checked=' + checked); to create an <a href> link the user can actually click on.
0

This should get what you need:

var checked = Array.prototype.slice.call(document.querySelectorAll('[name=selected]:checked'));
var values = checked.map(function(el) {
  return el.value;
});

console.log(values.join(','));

es6 version:

let checked = Array.from(document.querySelectorAll('[name=selected]:checked'));
let values = checked.map(el => el.value);

console.log(values.join(','));

1 Comment

Looks good to me - but how then would I go about extracting and printing the comma separated values to my url string? It looks as though it's retrieving them properly, I just can't get them to actually display.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.