Установка того же имени атрибута для группы типов радиоприемников с помощью JS - PullRequest
1 голос
/ 01 марта 2020

Я пытаюсь построить что-то подобное динамически с помощью JS:

<p class = "questions">La norme HTML5 ne nécessite pas de guillemets autour des valeurs d'attribut.</p>
<input type = "radio" id = "sp" name = "question1" value = "true"> Vrai<br>
<input type = "radio" id = "sp" name = "question1" value = "false"> Faux<br>

<p class = "questions">L'élément &lt;div&gt; est un élément non sémantique.</p>
<input type = "radio" id = "sp" name = "question2" value = "true"> Vrai<br>
<input type = "radio" id = "sp" name = "question2" value = "false"> Faux<br>

Однако в консоли мой код выглядит сейчас так:

<form id="quizz">
<p class="questions">La norme HTML5 ne nécessite pas de guillemets autour des valeurs d'attribut.
<input type="radio" id="sp" value="true" name="vrai">
<input type="radio" id="sp" value="false" name="faux">
</p>
<p class="questions">L'élément &lt;div&gt; est un élément non sémantique.
<input type="radio" id="sp" value="true" name="vrai">
<input type="radio" id="sp" value="false" name="faux"></p>

Очевидно, мой текущий код JS выглядит ужасно так:

questions = questionnaire.length;
newForm = document.createElement("form");
newForm.id = "quizz";
newTitle = document.createElement("h1");
for (i = 0; i < questions; i++) {

newParagraph = document.createElement("p");
newParagraph.classList = "questions";

newInput = document.createElement("input");
newInput.type = "radio";
newInput.id = "sp";
newInput.value = "true";
newInput.name = "vrai";

newInput1 = document.createElement("input");
newInput1.type = "radio";
newInput1.id = "sp";
newInput1.value = "false";
newInput1.name = "faux";

Я пытался создать al oop в l oop и другом методе slice и setattribute, но ни один из этих способов не работает или даже не работает. имеет смысл для меня.

Извините за вопрос noob и большое спасибо за помощь.

1 Ответ

0 голосов
/ 01 марта 2020

Это помогает даже с более чем двумя возможными ответами на каждый вопрос:

function makeForm() {

const newForm = document.createElement( "form" );
document.querySelector(".container").appendChild(newForm);

// Instead of .map() you can use a for loop through the questions
questions.map((question, qIndex) => {

    // Each question with the radios is a p element
    const questionElement = document.createElement("p");
    // Set the question text
    questionElement.innerText = question;

    // Loop through the different possible answers. 
    // Two items for the two possible answers,
    // in each of two, [0] is value, [1] is the text in french
    [['true', 'Vrai'], ['false', 'Faux']].map(answer => {

        const radioElement = document.createElement( "input" );

        radioElement.setAttribute("type", "radio");
        // id has 'sp', question index and true or false
        radioElement.setAttribute("id", `sp-${qIndex}-${answer[0]}`);
        // name is 'q' and question index, it has to be the same for each question
        radioElement.setAttribute("name", `q${qIndex}`);
        // value is true or false, the string you want when form is submitted
        radioElement.setAttribute( "value", `${ answer[ 0 ]}`);

        // Create label connected to each answer
        const label = document.createElement('label');
        // Needs a for attribute to connect id to the id of this radio
        label.setAttribute( "for", `sp-${ qIndex }-${ answer[ 0 ]}`);
        // Label text is 'vrai' or 'faux'
        label.innerText = answer[1];

        questionElement.appendChild(radioElement);
        questionElement.appendChild(label);

    });

    newForm.appendChild(questionElement);

});

Вы можете получить результаты при отправке: form[question], где form - элемент, а question - * 1007. *, "q1" в течение 1 oop и c.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...