newbietocoding
newbietocoding

Reputation: 65

Populate Radio buttons from an array in jquery

I have an array of the kind ["aaa", "bbb", "ccc"].

I am trying to take the value of individual indexes and display them as radio buttons in a dialog box. Can someone please help me how can I populate the radio buttons with the values of the array ?

Thanks.

Upvotes: 1

Views: 2268

Answers (3)

Grant Noe
Grant Noe

Reputation: 1003

Working code for this scenario is straight-forward, as you'll see below:

let myArray = ["aaa", "bbb", "ccc"];
let radioHTML = "";

$.each(myArray, function( index, value ) {
  radioHTML += '<label><input type="radio" name="radio_group" value="' + value + '"> ' + value + '</label><br>';
});

$("#radio-group").html(radioHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="my-form">
  <p>Radio Group</p>
  <div id="radio-group"></div>
</form>

How the Code Works

One of your comments mentioned that you're fairly new to coding, so I'll explain some things from the code block above.

jQuery $.each()

I'm not going to explain this in depth because there's a great answer about different looping methods here (but you're going to need to sift past some string interpolation code): How to loop through array in jQuery?

HTML Radio Buttons

The format is like this:

<label><input type="radio" name="radio_group" value="value">Visible Value</label><br>

Let's step through the non-obvious elements and attributes above:

name must be the SAME on every radio button for the same question. This is how the browser associates the radio buttons together, and prevents the user from selecting more than one at the same time. This name is also what gets passed as the "key" (in a key/value pair with the "value") during a form submission, but that's another topic.

value is what you're really asking about. This is the attribute where you set the behind-the-scenes value that will get passed to whatever code handles the form submission. In the working code snippet above, I've set the value and visible value as the same-- note that this isn't always the desired functionality.

Visible Value is just a string that sits OUTSIDE of the input element. This is because all it really is, is an text that displays for the user the value of your option. Depending upon your DOM structure and goals, you might want to wrap this in a <p> or <label.

<label></label> is the element that I use to wrap the entire input element, as well as the Visible Value. This allows the user to click on the Visible Value text to select the associated radio input.

<br> is an HTML line break. I put this here because elements have a tendency to be inline when you'd prefer that they be blocked (on separate lines). This will fix that problem.

Upvotes: 2

Jer
Jer

Reputation: 21

There is a very similar thread about this on stackoverflow. Basically you need to loop through the array and create each button dynamically.

In the thread I linked to, they use a for loop, but there are more modern ways to loop through the array:

Creating the buttons in JQuery is the same regardless of which looping method you choose.

One side note, if you want to improve the performance of rendering the buttons consider serializing all the dynamic buttons first, and then do one DOM manipulation using Jquery's html() method.

A clean way to accomplish this is to use Javascript's Array map method:

<span id="buttonArea"></span>

<script>
    var options = ["aaa","bbb","ccc"];
    var buttons = options.map((option,index) => {
        return '<input type="radio" id='+ option +
                     ' value='+ index +
                     ' name="button_group"/><label for='+ option +'>'+ option +'</label>';
    });

    $("#buttonArea").html(buttons.join(""));
</script>

Here is the dynamic button html created by this code:

<span id="buttonArea">
   <input type="radio" id="aaa" value="0" name="button_group"><label for="aaa">aaa</label>
   <input type="radio" id="bbb" value="1" name="button_group"><label for="bbb">bbb</label>
   <input type="radio" id="ccc" value="2" name="button_group"><label for="ccc">ccc</label>
</span>

Here is a working example I put up on W3CSchool.

Notes:

  • JQuery's html() is faster than append(), see benchmark in this thread
  • The join() method removes the commas from the output array the map method returns.
  • Using the Template Literal backtick ` makes the code easier to read, but it isn't supported in IE (and Edge doesn't support escaping template literals)

Upvotes: 2

Dalsier
Dalsier

Reputation: 397

You can use the reduce javascript function to create the inner html like this:

var innerHtml = array.reduce((groupHtml, currentValue) => groupHtml += `<input type="radio" name="radio_group" value="${currentValue}"/> ${currentValue}<br>`, '');

Then you can add the inner html to the desired container like this:

$('container').append(innerHtml);

Where container should be a valid selector for example: $('form'), $("#my-form"), etc...

Upvotes: 0

Related Questions