vloryan vloryan - 20 days ago 7
Javascript Question

Add checkbox values to a link using javascript

I would like to add checked checkbox values as url parameter to my link.
This is what I have amongst others:

<input id="box1" type="checkbox" class="checkbox" value="bx1=1"> <label for="box1"></label>
<input id="box2" type="checkbox" class="checkbox" value="bx2=1"> <label for="box1"></label>

<script>
$(".checkbox").on("change", function() {
var values = [];
$('.checkbox:checked').each(function() {
var result = $(this).val();
values.push(result);
});
var key = $(".link").html(values.join("&"));
document.write('<a href="http://www.example.com/test.html?' + key + '">Open here</a>');
});
</script>


The expected result is "http://www.example.com/test.html?bx1=1&bx2=1".
I hope someone can help me with this.

Answer

You can do like this:

<input id="box1" type="checkbox" class="checkbox" value="bx1=1"> <label for="box1"></label>
<input id="box2" type="checkbox" class="checkbox" value="bx2=1"> <label for="box1"></label>
<a class="link" href="http://www.example.com/test.html">Open here</a>

<script>
    $(".checkbox").on("change", function() {
        var values = [];
        $('.checkbox:checked').each(function() {
            var result = $(this).val();
            values.push(result);
        });
        $(".link").attr('href', 'http://www.example.com/test.html?' + values.join("&"));
    });
</script>