shoaib
shoaib

Reputation: 129

How to create radio buttons dynamically with array elements as label for buttons

I want to create radio buttons according to the elements of array that i am calling from database. and this elements should be use as label for each radio button. How i can code for it. I am calling 6 element as username suggestion. and when a guest select any of button then that label for particular button will replace the input name type by guest. Thank You

Upvotes: 2

Views: 5705

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29277

function showSuggestions() {
  var usernames = [
    'test1', 'test2', 'test3', 'test4'
  ];
  
  var result = $('#result');
  result.html('');

  for (var i = 0; i < usernames.length; i++) {
    result.append('<label><input type="radio" name="usernames" value="' + usernames[i] + '" /> ' + usernames[i] + '</label>');
  } 
}
                      
$('button').click(showSuggestions);

$('#result').on('change', 'input', function() {
  var elem = $(this);
  if (elem.is(':checked')) {
    $('#search').val(elem.val());
  }
});
label {
  display:block;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="search" type="search" /><button>Search</button>

<div id="result"></div>

Upvotes: 4

Related Questions