Data Attributes to Pass Data

HTML

<form class="question-page">
  
  <h1 class="title">Title</h1>
  <ul class="answers">
    <!-- possible answers will go here -->
  </ul>
  
  <button>Submit</button>
</form>

CSS

/*
  Data Attributes
  -----
  We want to add a list of questions with the ability to link between them. To do this, we will use data attributes. These look something like `data-propname` and work as HTML attributes on the element. Anything prepended with `data-` will become a "data attribute" which means it's a custom attribute. They will also be available on the node's `.dataset` property.
  
  1. Add a new element to hold our questions
  2. Write a function to render all links to questions
  3. Add `data-question-id` to each link
  4. Add event listener for link clicks
  5. Pull id from the data attribute and render the question with that id
  
  Only tasks we need to deal with data attributes:
  1. Add data as `data-propname`
  2. Pull data from `data-propname` or `.dataset`
*/


.questions {
  margin: 1em;
}

JavaScript

var questions = [
  {
  	id: 1,
    title: 'What color is the sky?',
    answers: ['Blue', 'Green', 'Orange', 'Purple'],
    correctAnswer: 0
  },
  {
  	id: 2,
    title: 'What color is grass?',
    answers: ['Red', 'Green', 'Yellow', 'Orange'],
    correctAnswer: 1
  },
  {
  	id: 3,
    title: 'What color is the ocean?',
    answers: ['Green', 'Orange', 'Purple', 'Blue'],
    correctAnswer: 3
  },
  {
  	id: 4,
    title: 'What color is snow?',
    answers: ['Blue', 'Green', 'Yellow', 'White'],
    correctAnswer: 3
  }
]

function renderQuestion(question) {
  var $form = $('.question-page')
  
  $form.find('.title').text(question.title)
  
  var $answers = $form.find('.answers')
  $answers.empty()
  
	question.answers.forEach(function(answer) {
  	var $li = $('<li>')
    var $radio = $('<input>', { type: 'radio', name: 'answer' + question.id  })
    var $label = $('<label>', { text: ' ' + answer }).prepend($radio)
    $li.prepend($label)
  	$answers.append($li)
  })
}

$(function() {
  renderQuestion(questions[0])
})