3

I have 3 groups of radio buttons each containing multiple ones. While using the data-toggle="buttons" in bootstrap3 for each group I can make sure, only one answer is selected per group. So far everything is fine.

The function below is triggered on a click event and returns the values of the selected items. My problem is how can I handle the returning values stored in the array values and give each key a name corresponding to the group set of buttons.

Assuming I select Red + small + Circle then getValues will return the key=> values :

  • [0] => Red
  • [1] => Small
  • [2] => Circle

Now, if I select small + Circle :

  • [0] => Small
  • [1]=> Circle

The values are stored as per the order of selection, Im trying to get this values to build a query as per the selection..

Where I want the values to be store in this format :

  • [color] =>x
  • [size] => y
  • [shape] => z

d

<input type="radio" name="color" value="red"/> Red     /// Grp 1 Color
<input type="radio" name="color" value="blue"/> Blue
<br/>
<input type="radio" name="size" value="small"/> small   /// Grp2  Size
<input type="radio" name="size" value ="Large"/> Large
<br/>
<input type="radio" name="shape" value="circle"/> Circle  /// Grp3 Shape
<input type="radio" name="shape" value="square"/> Square


function getValues(){

var values = [];
for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
       values.push(radios[x].value);
    }
}
return values;

}

$( "#Btn" ).click(function() {
      var x = getValues();

$.each(x, function(k, v) {

//display the key and value pair
      alert(k + ' is ' + v);

});

Thanks

6
  • 3
    Arrays do not have index names you want an object Commented Jan 28, 2014 at 13:02
  • 1
    stackoverflow.com/questions/11677033/… This might help you Commented Jan 28, 2014 at 13:06
  • there is no associative array in javascript Commented Jan 28, 2014 at 13:07
  • You can perhaps specify the value attributes as color:red, size:small etc. instead of just red, small etc. And then split and have your own keys easily by processing what you get. Commented Jan 28, 2014 at 13:12
  • Thanks, I was not aware the absence of associate arrays in javascript... @Chavan - Thanks for the useful link Commented Jan 28, 2014 at 13:14

5 Answers 5

1

Try this one.

LIVE DEMO

I think Associate array is possible in Javascript.

http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html

<input type="radio" name="color" class="radioGrp" value="red"/> Red  
<input type="radio" name="color" class="radioGrp" value="blue"/> Blue
<br/>
<input type="radio" name="size" class="radioGrp" value="small"/> small
<input type="radio" name="size" class="radioGrp" value ="Large"/> Large
<br/>
<input type="radio" name="shape" class="radioGrp" value="circle"/>circle
<input type="radio" name="shape" class="radioGrp" value="square"/>square

<input type='button' id="Btn" />


function getValues(){

var values = [];
var radios = document.getElementsByClassName("radioGrp");
    console.log(radios);

for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
       values[radios[x].name] = (radios[x].value);
    }
}
  return values;
}

$("#Btn").click(function() {
      var x = getValues();

     alert(x["color"]);
     alert(x["size"]);
     alert(x["shape"]);

     for(var prop in x ){
       alert( prop + " is " + x[prop] );
     }

});

You can't use $.each for asscioate array for more details http://bugs.jquery.com/ticket/4319

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

Comments

1

As mentioned already, Arrays are treated differently in JS. What you really want is a Hash Table... which is JS is just an object (sort of).

A technique you can use is to create an Array-Like object that has both the names as keys and indexes.

It's important to note that this isn't a full featured array-like object because it doesn't implement push, pop, slice, etc...

var values = {},
    length = 0;

for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
        //Assign the name as a key on the object
        values[radios[x].name] = radios[x].value;

        //Also assign the index as a key
        values[x] = radios[x].value;

        length += 1;
    }
}

values.length = length;

return values;

So what does this do for you exactly?

Well, it allows you to access the individual items by key:

values['bob'];

And it also allows you to access them by index:

values[0];

Even better, you can iterate over them using a normal for loop:

for(var i = 0; i < values.length; i++){
   //I act just like an array!!
   values[i];
}

2 Comments

Thanks alot Josh. Jus the part assign the index as a key shouldn't be values[x] = radios[x].name; instead ?
@user3003977 - I guess it just depends on if you want the names in there or the values.
0

Please use the code below:

    function getValues(){

    var values = [];
    for(var x = 0; x < radios.length; x++){
        if(radios[x].type == "radio" && radios[x].checked){
            var tmp={};
            tmp[radios[x].name]=radios[x].value;  
           values.push(tmp);
        }
    }
    return values;

    }

    $( "#Btn" ).click(function() {
          var x = getValues();

    $.each(x, function(k, v) {

    //display the key and value pair
          alert(k + ' is ' + v);

    });

Comments

0

This sample code below get all selected checkbox as array

// A function that return an array with the selected items
function getSelected() {

  var selected = [];

  var checkboxes = $('input[type=checkbox]:checked');

  for(var i = 0; i < checkboxes.length; i++){
     if(checkboxes[i].checked){
        selected.push(checkboxes[i].value);
     }
  }

  return selected;

}

Note that this work with jQuery.

Comments

0

Your code could look something in line of this:

<script>
function getValues() {
  var values={};
  var inputs = document.getElementsByTagName("input");
  console.log(inputs);
  for (var i=0;i<inputs.length;++i) 
     if (inputs[i].type==="radio" && inputs[i].checked) 
        values[inputs[i].name]=inputs[i].value;
 console.log(values);
}
</script>
<button onclick="getValues()">Hit me</button>

I know this is not jQuery - but you should be able to convert it :)

This will create an object from which you can pick the key-values pairs in proper order:

[ values.color||"default", values.size||"default", values.shape||"default" ]

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.