rctfan1999 rctfan1999 - 5 months ago 18
Javascript Question

Javascript - Checkboxes and Passing Values Though GET (No PHP)

I am attempting to use a form with checkboxes, and when submitted the form submits the selection over GET. My problem is that my project requires me to process these values using no PHP and only Javascript. When I use the script attached it processes the last one only, not the first. Below is the form with the checkboxes:

<fieldset id="fruitsVegetables[]">
<div class="foodObject">
<b>Fresh Baby Carrots</b><br>
<input class="pepLightCheckboxinput" id="BabyCarrots" type="checkbox" name="fruitsVegetables[]" value="BabyCarrots">
<label for="BabyCarrots">
<span><span></span></span>Choose
</label>
</div>

<div class="foodObject">
<b>Assorted Fresh Fruit</b><br>
<input class="pepLightCheckboxinput" id="AssortedFruit" type="checkbox" name="fruitsVegetables[]" value="AssortedFruit">
<label for="AssortedFruit">
<span><span></span></span>Choose
</label>
</div>

<div class="foodObject">
<b>Assorted Fruit Cups</b><br>
<input class="pepLightCheckboxinput" id="AssortedFruitCups" type="checkbox" name="fruitsVegetables" value="AssortedFruitCups">
<label for="AssortedFruitCups">
<span><span></span></span>Choose
</label>
</div>
</fieldset>


Here is my existing Javascript that I am using to process the variables:

var fruitsVegetables1 = getUrlVars()["fruitsVegetables[]"];
var fruitsVegetables2 = getUrlVars()["fruitsVegetables[]"];

function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}

console.log(fruitsVegetables1);
console.log(fruitsVegetables2);

Answer

A JavaScript object can have only one property for a given property name. That is, it can have only one property named "fruitsVegetables[]", so when vars[key] = value is called for the second time for the same value of key, it is replacing the previously set value.

Perhaps you should change your function to return an array instead. It could also be an array of just the values for a given parameter name.

var fruitsVegetablesArray = getUrlParamValues("fruitsVegetables[]");

function getUrlParamValues(paramName) {
    var values = [];
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        if (key == paramName) {
            values.push(value);
        }
    });
    return values;
}