0

How would i create a dynamic variable name based on all the forms input checkbox list names? This is what i have so far

var nameArray = [];
$.each($("#store-filter input").serializeArray(), function(i, field) {
    nameArray[field.name] = field.value;
});

alert(nameArray[0]);

for (i = 0; nameArray.length > i; i++)
{
     //alert(nameArray[i]);
     var nameArray[i] = nameArray[i].value;
     var nameArray[i]+'_checked_values' = $(\'input[name="nameArray[i]+[]"]:checked\').map(function() {
        return this.value;
    }).get();

}
alert(make); //variable name from name="make[]"

sample HTML

<form id="store-filter" action:"javascript:void(0);">
            <span id="store">
                <input id="store_0" value="2" name="store[]" type="checkbox">&nbsp;<label for="store_0">Store 1</label>
                <input id="store_1" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_1">Store 2</label>
                <input id="store_2" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_2">Store 3</label>
            </span>
            <span id="make">
                <input id="make_0" value="2" name="make[]" type="checkbox">&nbsp;<label for="make_0">make 
        1</label>
              <input id="make_1" value="3" name="make[]" type="checkbox">&nbsp;<label for="make_1">make 
        2</label> 
    <input id="make_2" value="4" name="make[]" type="checkbox">&nbsp;<label for="make_2">make 
        3</label>

             </span>
            <span id="time">
               <input id="time_0" value="2" name="time[]" type="checkbox">&nbsp;<label for="time_0">time 1</label>
              <input id="time_1" value="3" name="time[]" type="checkbox">&nbsp;<label for="time_1">time 2</label>
    <input id="time_2" value="4" name="time[]" type="checkbox">&nbsp;<label for="time_2">time 3</label>
            </span>
</form>

so later on in my code i can create a url string ?make=1,2,3&store=40,5,6&time=1,2,3,4 etc

the $_GET parameters are taken from the input check boxes name's dynamically

11
  • 3
    Can you explain your problem a little more as it's not clear what you're trying to do. In the first instance it seems like you want an object, not an array, so you can associate values to keys. However I don't see the relevance of this in your second code snippet, where you generate an array of selected value using map...? Commented Oct 28, 2014 at 7:59
  • 1
    What does "i want make and make[] dynamically" mean? Commented Oct 28, 2014 at 7:59
  • @RoryMcCrossan sorry about that, updated question. and added more of my code Commented Oct 28, 2014 at 8:20
  • @Vohuman updated question, and added more of my code Commented Oct 28, 2014 at 8:23
  • Still need to explain why you want to do this? Commented Oct 28, 2014 at 8:25

3 Answers 3

1

I'd suggest the following approach, obviously I'm binding to the click of a button, you should add that to the event/interaction of your choice:

function makeQueryString() {
  function keyValues(idPref) {
    // using the pass-in 'id' as a key:
    var key = idPref,
    // searching within the element identified with that 'id' for
    // other elements whose 'id' *starts* with that string:
      values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() {
        // iterating over those found elements and, if the value is *not* the
        // defaultValue (value on page-load), *or* the checked state is not the
        // default state (checked/unchecked as on page-load):
        if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) {
          // we return the value:
          return this.value;
        }
      // get() converts to a JavaScript Array, join() concatenates Array elements
      // to form a string:
      }).get().join(',');

    // if there is a key, and there are associated values, we return a 'key=value,value2'
    // string, otherwise we return an empty string:
    return key && values.length ? key + '=' + values : '';
  }

  // we return the value obtained after iterating over the form's span elements
  // that have an [id] attribute:
  return $('form span[id]').map(function(){
    // obtaining the 'key=value1,value2' strings from the called-function:
    return keyValues(this.id);
  // converting those returned elements into an Array, and joining with & characters:
  }).get().join('&');
}

$('#test').click(function(e) {
  e.preventDefault();
  console.log(makeQueryString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test</button>
<form id="store-filter" action: "javascript:void(0);">
  <span id="store">
                <input id="store_0" value="2" name="store[]" type="checkbox">&nbsp;<label for="store_0">Store 1</label>
                <input id="store_1" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_1">Store 2</label>
                <input id="store_2" value="3" name="store[]" type="checkbox">&nbsp;<label for="store_2">Store 3</label>
            </span>
  <span id="make">
                <input id="make_0" value="2" name="make[]" type="checkbox">&nbsp;<label for="make_0">make 
        1</label>
              <input id="make_1" value="3" name="make[]" type="checkbox">&nbsp;<label for="make_1">make 
        2</label> 
    <input id="make_2" value="4" name="make[]" type="checkbox">&nbsp;<label for="make_2">make 
        3</label>

             </span>
  <span id="time">
               <input id="time_0" value="2" name="time[]" type="checkbox">&nbsp;<label for="time_0">time 1</label>
              <input id="time_1" value="3" name="time[]" type="checkbox">&nbsp;<label for="time_1">time 2</label>
    <input id="time_2" value="4" name="time[]" type="checkbox">&nbsp;<label for="time_2">time 3</label>
            </span>
</form>

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks for the detailed explanation. if store and time are not checked, the url looks like this make=5,37&&&& i could remove the trailing &&&& after the url is generated, but for the sake of learning. how would i do in your code?
0

You are in Javascript, you do not need to declare the size of your arrays, there is no propblems by adding/removing anything from an Object/Array.

You should create a variable make then get the values in. Finally, you will be able to get it back.

var make;
$.each($("#store-filter input").serializeArray(), function(i, field) {
    make[i] = field.name;
});

Later in your code, you will use the array make.

make[0];

EDIT:

Here is an example i did for you: http://jsfiddle.net/kjkzm8qm/

NOTE: Your $.each($("#store-filter input").serializeArray() ... is useless, you should select all your inputs by adding a class AND, you should END your input tags by adding a / at the end.

HTML

 <input name="test" class="inputs" />

JAVASCRIPT

 $.each($(".inputs"), function(){ });

6 Comments

updated question, and added more of my code. getting an undefined error
Why do you use alert(make) when your variable is nameArray ? :o You should try console.(nameArray), then open your console within Firefox/Chrome
i assumed that since the input name is make the dynamic variable name created would be make too :P
Nha, sorry for the confusion, your variable is stored into nameArray !
i see, is there a way to make the variable name based on the input names? make, store, time etc ?
|
0

Update for david's answer.

If you want to remove & then add this code below

For this check the key value is not null

let keyValue = keyValues(this.id);
        if (keyValue != ''){
            return keyValue;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.