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?

Community
  • 1
  • 1
jongoeson
  • 43
  • 2
  • 8
  • Are you actually using jQuery or not ? – Robiseb Oct 12 '16 at 20:27
  • Try with `var checkedValues = $('.products:checkbox:checked').map(function() { return $(this).attr('value'); });` – DCruz22 Oct 12 '16 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] (http://jquery-howto.blogspot.co.uk/2013/02/jquery-test-check-if-checkbox-checked.html) or [link] (http://www.tutorialrepublic.com/faq/how-to-get-the-values-of-selected-checkboxes-in-a-group-using-jquery.php) – jongoeson Oct 12 '16 at 20:34
  • 1
    [jQuery](https://jquery.com/) 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. – Robiseb Oct 12 '16 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 :) – jongoeson Oct 12 '16 at 20:51

3 Answers3

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

Robiseb
  • 1,576
  • 2
  • 14
  • 17
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>
jack blank
  • 5,073
  • 7
  • 41
  • 73
  • 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? – jongoeson Oct 12 '16 at 21:02
  • 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()** http://stackoverflow.com/a/7031408/1893672. That does something after you click a checkbox – jack blank Oct 12 '16 at 21:07
  • Thanks for that! What I'm trying to do is generate a link when the checkboxes on the following page are clicked: [link] (http://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. – jongoeson Oct 12 '16 at 21:16
  • 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. – jack blank Oct 12 '16 at 21:24
  • 1
    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! – jongoeson Oct 12 '16 at 21:31
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(','));
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • 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. – jongoeson Oct 12 '16 at 20:48