1

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.

Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
newbietocoding
  • 55
  • 1
  • 1
  • 9
  • 1
    Please elaborate on what issue you are having with doing this yourself. Something is stopping you from doing this yourself. Detail those things. – Taplar Jun 13 '19 at 18:59
  • Okay so, I am a newbie and what I have tried till now is appending the values of array to my div. However I do not know how to append the values to individual radio buttons. I have zero idea about it and I would like to have a direction in which I can move forward to solve the issue. I have tried searching but have not found anything. – newbietocoding Jun 13 '19 at 19:11
  • Please show us what you have done in regards to appending the values to the div. And then, what part of appending a radio button to the div is confusing you? – Taplar Jun 13 '19 at 19:13

3 Answers3

2

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.

Grant Noe
  • 985
  • 8
  • 29
  • Hey, thanks for the detailed answer !! Could you please guide me on how can I get the values of the radio buttons ? What I mean is, I need to get the value of the radio button selected and store it in the database. Thanks !!!! – newbietocoding Jun 15 '19 at 07:26
  • @newbietocoding I think that that question departs from relevance to this particular Q/A— I’d recommend doing a search regarding “jquery form handling” or something similar. If you don’t find an answer that helps you solve your problem, you may open a new question. To point you in the right direction, check out serialize https://api.jquery.com/serialize/ and Ajax http://api.jquery.com/jquery.ajax/ ... make a strong effort to read and understand the docs, search for solutions to your hiccups, and toy with your code before posting a question here. That’s the best way to learn. – Grant Noe Jun 15 '19 at 08:29
  • Thank you so much Grant. I will surely do that. I just did not know what to look for exactly but now with your guidance, I can go ahead. Thank you so much. If you may, then could you please suggest books or resources to study java and jQuery. Thanks a ton. – newbietocoding Jun 15 '19 at 18:07
  • @newbietocoding books I’m not too sure about. Most of my research has come from having a problem and researching online for people who have experienced the same problem. That’s really what StackOverflow is all about. I’d bet that you’ll find most of what you need on this site (when you’re having an issue or you don’t know the best way to do something), and sites like W3Schools (which you should definitely check out for beginning knowledge). Most everything you’ll need or encounter has already been well-documented online. – Grant Noe Jun 15 '19 at 18:32
2

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)
Jer
  • 21
  • 4
  • Hey, Thanks The solution works for me, however, when I am trying to get the value of the selected radio button and update it to the database, it is not happening. Nothing happens basically. I also tried `code` var radioValue = $("input[name='gender']:checked").val();`code`and then tried alert radioValue. But nothing shows up. Could you please help me, how to get the values from the selected button and submit to the oracle database ? Or if not, could you please give me a direction . Thanks. – newbietocoding Jun 13 '19 at 23:04
0

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...

Dalsier
  • 377
  • 3
  • 14