Создание объекта с текстовым содержимым из элемента DOM и значений из элементов ввода? - PullRequest
0 голосов
/ 12 мая 2019

Я пытаюсь создать массив объектов со значениями текстового содержимого элемента HTML (метки) со своей страницы и значениями из входных данных формы.

Объект отображается в console.log, но в значениях нет ничего, он отображает «0».

//JavaScript
//answers value for the object
const answers = document.querySelectorAll("#questions input");

//questions value for the object
const questions = document.querySelectorAll("#questions label");

const questionsAnswers = [];
const wrongQuestions = [];
const displayDiv = document.getElementById("display");

  theQuestions.addEventListener("submit", (e)=>{
      for(let i = 0; i<questions.length; i++){

        //this is where the object gets created, where the problem occurs

            questionsAnswers.push({ question: questions[i].textContent, 
            answer: answers[i]});

        console.log(questionsAnswers[i]);
    }//end of for loop

        e.preventDefault();

 });// end of event listener


   //HTML
    <form id="theQuestions" style="height:500px">
        <div class="form-group">
          <label for="question1">What is the NBA team in Georgia?</label>
          <input type="text" class="form-control" id="question1">
        </div>
        <div class="form-group">
          <label for="question2">What is the name of the NFL team in 
          North Carolina?</label>
          <input type="text" class="form-control" id="question2">
        </div>
        <div class="form-group">
            <label for="question3">What team did Micheal Jordan play for? 
             </label>
            <input type="text" class="form-control" id="question3">
        </div>    
          <button type="submit" class="btn btn-outline 
           primary">Submit</button>        
    </form>



//I want the object to look like this 
 {
   answer: "text content of the first <label> element",
  question: "form input value from the first input element"
  },
  {
  answer: "text content of the 2nd <label> element",
  question: "form input value from the 2nd input element"
},
{
   answer: "text content of the 3rd <label> element",
   question: "form input value from the 3rd input element"
 }

1 Ответ

0 голосов
/ 12 мая 2019

Вы просто должны изменить эту строку:

questionsAnswers.push ({question: questions [i] .textContent, ответ: ответы [я]});

до

questionsAnswers.push ({question: questions [i] .textContent, ответ: ответы [i] .value});

Я надеюсь, что это будет работать

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