samedi 30 mai 2020

Using Jquery how do I get dynamically generated checkboxes checked status inside a function called on a button click

Using jquery, coming out of an ajax call I have an 'each' statement that generates checkboxes. Here is the line that actually does the generation and append inside my script.

$('<input />', { type: 'checkbox', id: value.rental_accessories_id, value: value.partnumber, class: 'accessories' }).appendTo($('#form_container');

On a click of a button I am executing a function in the main HTML code.

<button type="button" onclick="calculate()" id="calc">CALCULATE</button>

Inside the function, so back in the script, I need to know if these checkboxes have been selected. I can grab the elements using this code and verify they are there, but cannot get a checked status:

    function calculate() {
$('#form_container input, #form_container select').each(
                function(index){  
                    var input = $(this);
                    console.log('Id:' + input.attr('id'));
                    console.log('Type: ' + input.attr('type'));
                    console.log('Name: ' + input.attr('name'));
                    console.log('Value: ' + input.val());
                    console.log($('#' + input.attr('id')).checked);
                    if(input.attr('type') == 'checkbox')
                    {
                        checked_status = input.parent().find('input[name="'+input.attr('name')+'"]:checked').val();
                        console.log('Checked Status' + checked_status);
                    }
                }
            );
}

The id, type, name, and value are coming through find. But I am getting a 'undefined' on the checked status request. I've tried two different methods that are shown here but both of them return undefined. I'm creating a couple other form field types which is why I am looking for both input and select. I can find everything else I am looking for except whether or not the checkboxes have been checked.

I've already done some digging on this site looking for an answer. You might recognize some of the code above as coming from suggestions from other questions that are similar. I'm not an expert on jquery but a lot of the suggestions mention using .on, but the examples do not seem to apply to what I am doing, or if they do apply I am not sure how to implement them for this specific setup.




Aucun commentaire:

Enregistrer un commentaire