0

I'm using Handlebars.js to output a series of question/answer forms. There is only 1 answer per question so I'm using <input type="radio">. The code below produces the desired results however when a radio button is checked the jQuery change event is not firing.

<script id="questions-template" type="text/x-handlebars-template">
{{#questions}}
{{questionIndex @index}}
<article class="question question-{{@index}} clearfix">
  <h2>{{question}}</h2>
  <form>
    {{#each answers}}
    <div class="answer">
      <input type="radio" name="radios[{{../questionIndex}}]" id="radios-{{../questionIndex}}{{@index}}" value="{{value}}">
      <label for="radios-{{../questionIndex}}{{@index}}"><span>{{answer}}</span></label>
    </div>
    {{/each}}
  </form>
</article>
{{/questions}}
</script>
<div id="questions"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script>
$(function(){
  var questions = {
    "questions": [
      { 
        "question": "Lorem ipsum dolor sit amet, consectetur adipiscing elit?", 
        "answers": [
          { 
            "answer": "Answer 1",
            "value": 1
          },
          { 
            "answer": "Answer 2",
            "value": 2
          }
        ]
      }
    ]
  };

  $(document).ready(function(event) {
    var
    source = $("#questions-template").html(),
    template = Handlebars.compile(source);
    Handlebars.registerHelper('questionIndex', function(value) {
      this.questionIndex = Number(value);
    });
    $('#questions').append(template(questions));
  });

  $('input:radio').change(function(event) {
    alert('change');
  });
});
</script>
Allan Thomas
  • 3,481
  • 5
  • 26
  • 29

1 Answers1

1

you should be using .on to assign your event handler - because your radio button is generated dynamically. try this:

  $("#questions").on("change", "input:radio", function(event) {//assuming questions is already part of the DOM
    alert('change');
  });

this question here Why use jQuery on() instead of click() gives some good insight over attaching event handlers to dynamically generated elements

Community
  • 1
  • 1
Birgit Martinelle
  • 1,869
  • 1
  • 12
  • 9