Suppose my javascript called server(AJAX call) and then got server response with an array of data : dataArray.
the number of data in the dataArray will be either 1 or 2 or 3, that’s no more than 3.
I would like to show the data as radio button selections. Since the number of data is dynamic(1 or 2 or 3), so I should show radio buttons dynamically.
I came up with two ways to do this:
1st way: have three radio buttons in the HTML:
<div id="my-radio-btns">
<input id="data0" type="radio" name="datas" value="0"><label for="data0"></label>
<input id="data1" type="radio" name="datas" value="1"><label for="data1"></label>
<input id="data2" type="radio" name="datas" value="2"><label for="data2"></label>
</div>
then, hide and show certain number of the above radio buttons based on the number of data in the dataArray.
2nd way: use javascript to append radio button HTML strings:
for(var i=0; i<dataArray.length; i++){
$('#my-radio-btns').append("<input id='data"+i+"type='radio' name='datas' value="+i+"> <label for='data"+i+"></label>");
}
I am wondering, which way is better?
As you already have a couple of solutions it really comes down to a discussion on the merits of each.
With the first approach:
visibility:hidden, the latter will reserve the space in the page
layout such that there is no shifting of elements as you display them.
button to the markup?
The second approach:
manipulation is quite minimal, but one of the most expensive
operations in jquery is modifying the DOM. Just something to think about.
Also, may I suggest a little enhancement to the second code sample:
Prevents multiple lookups of the my-radio-btns element – won’t make a huge amount of difference over the space of 3 elements but if you increase this is may start of add up.