0

I am building a mcq forum and wanted to check whether the answer(radiobutton) is selected or not. I am getting mcq's from an api and creating forum dynamically. //Getting response from api

function getData() {
$.get('http://5d76bf96515d1a0014085cf9.mockapi.io/quiz', function (data, status) {
            var response = data;
            for (let i = 0; i < response.length; i++) {
                createNewElement(response[i].id, response[i].question, response[i].options)
            }
        }
        )
    }

//creating elements dynamically

function createNewElement(id, questions, options) {
    var newListElement = document.createElement('li');
    var textNode = document.createTextNode("Q: " + questions);
    newListElement.appendChild(textNode);
    list.appendChild(newListElement);
    for (let i = 0; i < options.length; i++) {
        radioYes = document.createElement('input');
        radioYes.setAttribute('type', 'radio');
        radioYes.setAttribute("id", id);
        radioYes.setAttribute("name", id);
var lblYes = document.createElement('label');
        /*create text node for label Text which display for Radio button*/
        var textYes = document.createTextNode(options[i]);

        /*add text to new create label*/
        lblYes.appendChild(textYes);

        /*add radio button to Div*/
        list.appendChild(radioYes);

        /*add label text for radio button to Div*/
        list.appendChild(lblYes);
        var spaceBr = document.createElement('br');
        list.appendChild(spaceBr);
        // getIds(radioYes.id);
    }
}

Now please tell me how to check these radio buttons for correct answer

  • In order for `radio` buttons to link together, they have to have the same `name=`. In your code you set both the name *and* the id to `id` - so either your radios have different names (so don't act as radios) or you have duplicate IDs - HTML documents must not have duplicate IDs - all IDs must be unique. – freedomn-m Apr 27 '20 at 13:34
  • they are working together I just want to check which radio button is checked so i can match the value of the selected radio button with the correct answer and can tell user that the selected option is right or wrong – M. Humza Javaid Apr 27 '20 at 13:40
  • Would be much easier if you provided an example HTML output. But from wading through all the ridiculously long vanilla javascript (why did you tag this jquery then use all that protracted code???) it looks like you have a `li` question with multiple radios, so a combination of `$("li").map` and `$(this).find(":checked")` - here's a simple example for you: https://jsfiddle.net/bg0k29jf/ – freedomn-m Apr 27 '20 at 13:43

0 Answers0