jack brone
jack brone

Reputation: 205

Selected Check box value display in URL with parameter using Php Javascript

I need to get selected check box value in browser url with parameter name.

My HTML code:

<div style="width:200px; float:left">
    Price
    <div>
    <input type="checkbox" name="price" value="0-1000" class="filters" />0-1000<br />
    <input type="checkbox" name="price" value="1000-2000" class="filters" />1000-2000<br />
    <input type="checkbox" name="price" value="3000-4000" class="filters" />2000-3000<br />
    </div>
    Colors
    <div>
   <input type="checkbox" name="colors" value="Red" class="filters" />RED<br />
    <input type="checkbox" name="colors" value="Green" class="filters" />GREEN<br />
    <input type="checkbox" name="colors" value="Blue" class="filters" />BLUE<br />
    </div>
    </div>

My Javascript Code

<script type="text/javascript">
$('.filters').on('change',function(){
    var price = new Array();
        $('input[name=price]:checked').each(function(){
           price.push($(this).val());
        });
    var colors = new Array();
        $('input[name=colors]:checked').each(function(){
           colors.push($(this).val());
        });

    location.href = 'http://localhost/test/javascript.php?price='+price;


});         
</script>

I need Browser Url like below, after selecting two prices and one color

 http://localhost/test/javascript.php?prices=0-1000,1000-2000&colors=Red

Upvotes: 1

Views: 1751

Answers (1)

Sebastian Nette
Sebastian Nette

Reputation: 7812

You are looking for .join()

The join() method joins the elements of an array into a string, and returns the string.

The elements will be separated by a specified separator. The default separator is comma (,).

location.href = 'http://localhost/test/javascript.php?price=' + price.join(',') + '&colors=' + colors.join(',');

Even though the comma seems to be the default separator , I would add it anyway just to be sure.

var url = 'http://localhost/test/javascript.php?';
if(price.length) {
    url += '&price=' + price.join(',');
}
if(colors.length){
    url += '&colors=' + colors.join(',');
}
location.href = url; // or url.replace('?&','?');

Upvotes: 2

Related Questions