0

Here is my problem. I need to generate dynamically differents forms with a switch function. forms are displayed step by step to present few questions with radio input with a value for the anwser.

function myFunctionSwitch() {
switch(myVarValue) {
case "something":
text = "<div id=\"q1\">Question
<label>Answer<input class=\"reponse\" type=\"radio\" name=\"q1\" id=\"q1r1\" value=\"462\">
<span class=\"checkmark\">
</span>
</label>
<label><input class=\"reponse\" type=\"radio\"... 
<label><input class=\"reponse\" type=\"radio\"... 
<label><input class=\"reponse\" type=\"radio\"... 
</div>"
break;
 default:...
}
document.getElementById("myModalInside").innerHTML = text;

I try to get input value with jQuery by this way:

$(document).ready(function(){   "use strict";
var result;
var value1;

$('#q1 .reponse').on('change', function(){  
    value1 = parseInt(this.value);
    result = value1 + ...;
});

This jQuery code does the right job from an html page with form write in. But I need my switch function to present different forms. That's why I need help.

1 Answers1

1

If you want to handle events on a dynamically added element you need to delegate event this way:

$(document).on('change', '#q1 .reponse' , function() {
    value1 = parseInt(this.value);
    result = value1 + ...;
});

More info here.

skobaljic
  • 9,379
  • 1
  • 25
  • 51
  • 2
    I would suggest using the smallest possible container, which would typically be the container where the elements are dynamically added, rather than `document`. But `document` is a good failsafe if you don't know for certain where the dynamic elements will be in the DOM. – Niet the Dark Absol Jul 02 '18 at 11:37
  • 1
    Thanks a lot for your help this is what I was looking for. – NOONETO NETWORK Jul 02 '18 at 12:05
  • this question is a duplicate because of my lack of English vocabulary. I was focused on my problem and the keywords did not come to me. English is not easy to read when one is lost in codes. I'm new here, I do not know if I need to erase my question. – NOONETO NETWORK Jul 02 '18 at 12:26