Abdul M. Diaz
Abdul M. Diaz

Reputation: 66

Insert radio with label using jQuery

I have created a JS quiz and it holds all the answer choices in arrays. The answer choices are then inserted into a created <input type="radio" . . . . /> element. However the choices, instead of being inside a label, they are held inside the input element alone. Here's to further expand what I'm talking about:

html-code1

I want it to be like this

html-code2

Here's the code that creates the inputs:

  // Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('<ul>');
    var item;
    var input = '';
    for (var i = 0; i < questions[index].choices.length; i++) {
      item = $('<li>');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += questions[index].choices[i];
      item.append(input);
    radioList.append(item);
    }
    return radioList;
  }

Any help would be greatly appreciated.

Upvotes: 0

Views: 121

Answers (1)

Charles
Charles

Reputation: 640

The label should really encompass the radio button for best practices. Try this:

// Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('<ul>');
    for (var i = 0; i < questions[index].choices.length; i++) {
      var item = $('<li>');
      var label = $('<label>');
      var input = $('<input>', {type: 'radio', name: 'answer', value: i});
      input.appendTo(label);
      label.append(questions[index].choices[i]);
      item.append(label);
      radioList.append(item);
    }
    return radioList;
  }

Upvotes: 1

Related Questions