Ho iniziato a creare un modulo dinamico utilizzando jquery per creare ogni domanda alla volta, ma sembra esserci un problema con un evento sul contenuto dinamico.
div class="container"> Add or Remove text boxes with jQuery
javascript
jQuery(document).ready(function($){ $('#box1').keyup(function () { var impt = '1. '+ $(this).val(); $(".preview").html(impt); }); $('#radio1').keyup(function () { alert("radio1"); var impt = 'Please choose'+ $(this).val(); appendTo(".preview").append(impt); //$(".preview").append(impt); }); $('.my-form .ansRadio').click(function(){//when radio answer is clicked show the radio answer options var n = $('.text-box').length; var box_html = $(''); box_html.hide(); $('.answer').hide(); $('.my-form div.text-box:last').after(box_html); box_html.fadeIn('slow'); return false; }); $('.my-form').on('click', '.remove-option', function(){ $(this).parent().css( 'background-color', '#FF6C6C' ); $(this).parent().fadeOut("slow", function() { $(this).remove(); $('.box-number').each(function(index){ $(this).text( index + 1 ); }); $('.answer').show(); }); return false; });
});
Sembra che ci sia un problema nel trovare il
$('#radio1').keyup(function ()
lavorare.
Ecco il jsfiddle
Come puoi vedere il link ‘remove option’ funziona ma il tipo nella casella delle opzioni non triggers la funzione keyup.
Qualsiasi aiuto molto apprezzato.
stai vincolando l’evento keyup quando l’elemento non è nel DOM, prova invece questo:
$('.my-form').on("keyup", "#radio1", function () {
In jQuery se si aggiunge un elemento a DOM DYNAMICALLY, quindi per albind un evento a quell’elemento è necessario scrivere o chiamare il codice per albind immediatamente l’evento dopo averlo accodato al DOM.
Codice aggiornato
jQuery(document).ready(function($){ $('#box1').keyup(function () { var impt = '1. '+ $(this).val(); $(".preview").html(impt); }); $('.my-form .ansRadio').click(function(){//when radio answer is clicked show the radio answer options var n = $('.text-box').length; var box_html = $(''); box_html.hide(); $('.answer').hide(); $('.my-form div.text-box:last').after(box_html); box_html.fadeIn('slow'); $('#radio1').keyup(function () { alert("radio1"); var impt = 'Please choose'+ $(this).val(); appendTo(".preview").append(impt); //$(".preview").append(impt); }); return false; }); $('.my-form').on('click', '.remove-option', function(){ $(this).parent().css( 'background-color', '#FF6C6C' ); $(this).parent().fadeOut("slow", function() { $(this).remove(); $('.box-number').each(function(index){ $(this).text( index + 1 ); }); $('.answer').show(); }); return false; });