Arun
Arun

Reputation: 1482

Jquery append values to a url as query string

I tried some jquery to append my check box checked values to the url as query string the code is working nice but when I check more than one checkbox the url will like this.....

Localhost:355/searchdatabase/?manufacturer=LG&manufacturer=Samsung&manufacturer=Test

But I need the url Like

Localhost:355/searchdatabase/?manufacturer=LG,Samsung,Test

here is my code

$(document).ready(function () {
    $('input[type="checkbox"]').on('change', function (e) {
        var data = [],
            loc = $('<a>', { href: window.location })[0];
        $('input[type="checkbox"]').each(function (i) {
            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);
        }
    });
});

My checkbox list groups code here

          <div class="rowElem">
          <input type="checkbox" name="manufacturer" id="">
          <label>LG</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="manufacturer" id="">
          <label>Samsung</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="manufacturer" id="">
          <label>Test</label>
        </div>




         <div class="rowElem">
          <input type="checkbox" name="material" id="">
          <label>iron</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="material" id="">
          <label>steel</label>
        </div>
        <div class="rowElem">
          <input type="checkbox" name="material" id="">
          <label>copper</label>
        </div>

I need Manufacturer as a group and material as another..

Upvotes: 0

Views: 467

Answers (1)

Elon Than
Elon Than

Reputation: 9775

You can add all manufacturers to separated array and then add as one field.

var manufacturers = [];
if (this.checked) {
    if (this.name === 'manufacturers') {
        manufacturers.push(this.value);
    } else {
        data.push(this.name + '=' + this.value);
    }
}

And before data = data.join('&'); add data.push('manufacturers=' + manufacturers.join(','));.

Upvotes: 1

Related Questions