Как вернуть массив на основе выбранного ответа в объекте - PullRequest
0 голосов
/ 28 января 2020

Если у меня есть объект, определенный как вопрос, как мне отобразить соответствующий массив в моем .inner HTML на основе выбора пользователя

, например

var questions = [
    {
        "question": "What area of the world are you thinking of discovering next?",
        "answer1": "Europe",
        "countryList1": "europeArray",
        "answer2": "Asia",
        "countryList2": "asiaArray",
        "answer3": "America",
        "countryList3": "americaArray",
        "answer4": "Australia",
        "countryList4": "australiaArray"        
    },
]

i Я пробовал несколько функций, но не могу отобразить правильный массив, который я создал для выбранных континентов, примеры функций, которые я создал ниже:

    var test_asia = asiaArray
    var test_america = americaArray
    var test_europe = europeArray
    var test_australia = australiaArray

    var chosenPlace = function test(questions){
        if (questions[0].answer1 == 'Europe') {
            return test_europe;
        } else if (questions[0].answer2 == 'Asia') {
            return test_asia;
        } else if (questions[0].answer3 == 'America') {
            return test_america;
        } else {
            return test_australia;
        }
    }

    result.innerHTML =
    `<h1 class="final-score">Our Recommendations:</h1>
    <div class="summary">
        <p><br></br></p>
        <p>${chosenPlace()}</p>
    </div>

1 Ответ

1 голос
/ 28 января 2020

Я сделаю что-то вроде этого:

    const questions = 
          [ { question: 'What area of the world are you thinking of discovering next?'
            , answer:
              [ { Europe   : 'europeArray'    }
              , { Asia     : 'asiaArray'      }
              , { America  : 'americaArray'   }
              , { Australia: 'australiaArray' }
            ] }
          , { question: 'Who do you intend to travel with?'
            , answer:
              [ { 'Myself'     : '6' }
              , { 'My Partner' : '3' }
              , { 'My Family'  : '1' }
              , { 'My Friends' : '6' }
            ] }
          ] 

получите ответ следующим образом:

const questions = 
      [ { question: 'What area of the world are you thinking of discovering next?'
        , answers :
          [ { Europe   : 'europeArray'    }
          , { Asia     : 'asiaArray'      }
          , { America  : 'americaArray'   }
          , { Australia: 'australiaArray' }
        ] }
      , { question: 'Who do you intend to travel with?'
        , answers :
          [ { 'Myself'     : '6' }
          , { 'My Partner' : '3' }
          , { 'My Family'  : '1' }
          , { 'My Friends' : '6' }
        ] }
      ] 


const formContainer = document.getElementById('form-container')
  ,   AnswerElm     = [...formContainer.querySelectorAll('label')]
                            .map(el=>
                              ({ op:el.querySelector('input')
                                ,sp:el.querySelector('span')
                            })) ;


console.log('AnswerElm', AnswerElm)

formContainer.onsubmit=e=>e.preventDefault();  // disable form submit

let  Q_Num = 0;
const Q_Num_max = questions.length;

function setQuestion(NoQuestion)
  {
  formContainer.reset();
  formContainer.question.value = questions[NoQuestion].question;
  AnswerElm.forEach((elm,i) =>
    {
      elm.sp.textContent = Object.keys(questions[NoQuestion].answers[i])[0]
      elm.op.value       = Object.values(questions[NoQuestion].answers[i])[0]
    })
  }
setQuestion(Q_Num)


formContainer.onclick=e=>
  {
  if (!e.target.matches('button')) return

  let elmBt = e.target.textContent

  if (elmBt == 'Next')
    {
    alert( formContainer.answer.value)
    Q_Num = ++Q_Num %Q_Num_max
    setQuestion(Q_Num)
    }
  }
/* QUESTIONNAIRE FORM */

.form-body {
  background-color: #ffd08a;
  display: flex;
  height: 900px;
}
#form-container {
  box-sizing: border-box;
  box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);
  padding: 3rem;
  width: 60%;
  margin: 5rem auto;
  display: flex;
  flex-direction: column;
  min-height: 70vh;
  background-color: #aea4ee;
  border: #666 1px solid;
}
#form-container input[type=radio] {
  -ms-transform: scale(1.5); /* IE 9 */
  -webkit-transform: scale(1.5); /* Chrome, Safari, Opera */
  transform: scale(1.5);
  margin-right: 1rem;
}

.title{
  margin-bottom: 3rem;
  font-weight: 400;
  font-size: 2.5rem;
  text-align: center;
  text-transform: uppercase;
}

#form-container output[name=question] {
  margin: 2rem 0;
  font-size: 1.5rem;
}
#form-container label{
  padding: 1rem;
  width: 80%;
  border-radius: 5px;
  transition: all 0.3s;
}
#form-container label:hover +span  {
  background: rgba(255, 255, 255, 0.4);
}
#form-container label input:checked +span {
  background: #08038c6c;
  color: #000;
}
#controls > * {
  margin: 1rem;
  margin-top: 3rem;
}

#controls button {
  padding: 1rem 2rem;

  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-size: 1rem;
  font-weight: 300;
  outline: none;
  transform: scale(0.98);
  transition: all 0.2s;

  color: #494949;
  text-transform: uppercase;
  text-decoration: none;
  background: #ffffff;
  border: 4px solid #494949;
  display: inline-block;
  transition: all 0.4s ease 0s;
}

#controls button:hover {
  color: #ffffff;
  font-weight: bold;
  background:	#7c00ff;
  border-color:#7c00ff;
  transition: all 0.4s ease 0s;
  cursor: pointer;
}

button.restart {
  background: orange;
  color: #00000050;
  font-size: 2rem;
  margin-bottom: 1rem;
  transition: all 0.4s;
}

button.restart:hover {
  color: #00000098;
  cursor: pointer;
}

.result {
  display: flex;
  flex-direction: column;
  padding: 2rem;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 2.5rem;
  min-height: 80vh;
}

.final-score {
  color: #00000099;
}

.summary {
  font-size: 1rem;
  text-shadow: 1px 1px #ffffff50;
  color: #00000099;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 0 2rem;
  margin-bottom: 2rem;
}

.summary h1 {
  align-self: center;
}
<section class="form-body">
  <form id="form-container">
    <div class="title">Questions</div>
    <output name="question"></output>
    <label class="option">
      <input type="radio" name="answer" value=""> <span></span>
    </label>
    <label class="option">
      <input type="radio" name="answer" value=""> <span></span>
    </label>
    <label class="option">
      <input type="radio" name="answer" value=""> <span></span>
    </label>
    <label class="option">
      <input type="radio" name="answer" value=""> <span></span>
    </label>
    <!-- BUTTONS -->
    <div id="controls">
      <button>Previous</button>
      <button>Next</button>
    </div>
  </form>
</section>

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