Search code examples
jquerydomelementprependcreateelement

How to get radio value in jQuery of a dynamically created input


I've got a problem, just can't get a value of an input that I created with a function in query generated by php.

First I generate a function that shows a proper content depending of which radio is checked. Some kind of sub level choice. This works fine but it seems that it's not registered as a DOM element.

Here is the function that generates a content with radios

    $( document ).ready(function() {    
    $('#f_49').change(function(event) {                     
        var selectedID = $(this);
        var html = '<div class="col-md-12 p-4" id="id_f_49">';
        html = html + '<div class="form-check">';
        html = html+'<input class="form-check-input" type="radio" name="f_49[]" id="f_49_4" value="129"'; 
        html = html+' checked >';
        html = html+ ' <label class="form-check-label" for="f_49_4">';
        html = html+' CHOICE</label>';      
        html = html+ '</div>';  
        html = html+ '</div>';

        $('.first_choice_div_group').each(function(){
            $(this).not(selectedID).prop('checked', false);
        });

        $('#target_div').html(html);
        $('#target_div').show('slow');
        });

});

Now the problem is, when I try to get values of all form elements, I get only those generated in php but those above created by jQuery NOT.

$('#user-form').contents().find('input[id*="f_"]').change(function(event) {
    var value = $(this).val();
    alert (value);
});

This function (or something similar) MUST but doesn't alert any value when I change #f_49_4. I've tried to append / prepend elements, but with no success, maybe someone can help with this. Thanks a lot.


Solution

  • You need to wire events up to elements that are already in the dom. You can use jQuery on for monitoring events for dynamically added elements.

    $('#user-form').on('change', 'input[id*="f_"]', function(event){
        var value = $(this).val();
        alert (value);
    });