0

I have some check box to get Brand name and size, i want to display value for selected check box in url box like

www.xyz.com?brands=P,Q,R&Size=2,3 

I've this code that shows,

 www.xyz.com?brands=P&brands=Q&brands=R&Size=2&Size=3

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$('input[type="checkbox"]').on('change', function(e) {
    var data = [],
        loc = $('<a>', {
            href: window.location
        })[0];
    $('input[type="checkbox"]').each(function() {
        if (this.checked) {
            data.push(this.name + '=' + this.value);
        }
    });
    data = data.join('&');

    $.post('/ajax-post-url/', data);
    if (history.pushState) {
        history.pushState(null, null, loc.pathname + '?' + data);
    }
});
</script>

HTML

<div class="pane">
    <div class="ele">
        <input type="checkbox" value="X" name="Brand">
        <label>Brand 1</label>
        <input type="checkbox" value="Y" name="Brand">
        <label>Brand 2</label>
        <input type="checkbox" value="Z" name="Brand">
        <label>Brand 3</label>
        <input type="checkbox" value="1" name="Size">
        <label>Size 1</label>
        <input type="checkbox" value="2" name="Size">
        <label>Size 2</label>
        <input type="checkbox" value="3" name="Size">
        <label>Size 3</label>
    </div>
</div>
Divyank
  • 740
  • 3
  • 20

2 Answers2

2

You can change your script this way:

$('input[type="checkbox"]').on('change', function(e) {
    var data = {}; // 1
    var dataStrings = []; // 2

    $('input[type="checkbox"]').each(function() { // 3
        if (this.checked) { 
            if (data[this.name] === undefined) data[this.name] = []; // 4
            data[this.name].push(this.value); // 5
        }
    });

    $.each(data, function(key, value) // 6
    {
        dataStrings.push(key + "=" + value.join(','));
    });

    var result = dataStrings.join('&'); // 7

    alert(result);

    $.post('/ajax-post-url/', data);
    if (history.pushState) {
        history.pushState(null, null, loc.pathname + '?' + data);
    }
});

Here is a JSFiddle: http://jsfiddle.net/8ct2mbpa/

This is how it works:

  1. data is an object which consists of ARRAYS of selected values
  2. dataStrings is an array which consists of key-value pairs

  3. First, we iterate through all selected checkboxes

  4. If such array is not yet presented, we create it. For example, data['Brand'] is an empty array now
  5. We add a selected value. data['Brand'] is now filled with values ['X', 'Y', 'Z']
  6. Combine values in key-value pairs. It now becomes Brand=X,Y,Z
  7. Join all key-value pairs using "&" sign
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
0

I think you're looking for this:

How do I pass a URL with multiple parameters into a URL?

That said, I think this question could be marked as a double.

Community
  • 1
  • 1
Taffer
  • 33
  • 7