I'm trying to use JavaScript to add parameters to the current URL in order to filter WordPress posts. Example: http://domain.com/houses/?rooms=1,2&bath=1&yard=yes
I have successfully done this with one of the parameters, but I'm failing in understanding how to add on multiple parameters. What is the proper way of getting this one?
Also, is using window.location.assign()
, the proper way for adding the parameters to the URL? Is using AJAX better/safer?
Below is my code
HTML
<div id="filter-rooms">
<ul>
<li>
<input type="checkbox" value="1" id="rooms" />1 Room</li>
<li>
<input type="checkbox" value="2" id="rooms" />2 Rooms</li>
<li>
<input type="checkbox" value="3" id="rooms" />3 Rooms</li>
<li>
<input type="checkbox" value="4" id="rooms" />4 Rooms</li>
</ul>
</div>
<div id="filter-bath">
<ul>
<li>
<input type="checkbox" value="1" id="bath" />1 Bathrooms</li>
<li>
<input type="checkbox" value="2" id="bath" />2 Bathrooms</li>
<li>
<input type="checkbox" value="3" id="bath" />3 Bathrooms</li>
</ul>
</div>
<div id="filter-yard">
<ul>
<li>
<input type="radio" name="yard" value="yes" id="yard" />Yes</li>
<li>
<input type="radio" name="yard" value="no" id="yard" />No</li>
</ul>
</div>
JavaScript
$('#filter-rooms').on('change', 'input[type="checkbox"]', function () {
var $ul = $(this).closest('ul'),
vals = [];
$ul.find('input:checked').each(function () {
vals.push($(this).val());
});
vals = vals.join(",");
window.location.assign('?rooms=' + vals);
});
Now, in the JavaScript displayed above, I managed to get the rooms parameter successfully working, but when I duplicate this for the other parameters, it replaces the URL with the rooms parameter instead of adding it on to the end of the URL like so - &bath=1&yard=yes
jsFiddle: http://jsfiddle.net/g9Laforb/1/ (Note: window.location.assign() is missing because jsFiddle doesn't allow it.)
Any advice on this would be greatly appreciated.