Function for all checkboxes

0

Good day. I need to make a function that works for all the checkboxes of a form, this function should create an input with the id equal to the id of the selected checkbox and when deselecting the checkbox the input should be deleted.

I have the following function but it does not work correctly.

    $(function() {
    $("input[type='checkbox']").click(function() {
        if ($(this).is(':checked') ) {
            var y = $("input:checked").attr("id");
            var x = document.createElement("INPUT");
            x.setAttribute("type", "text");
            x.setAttribute("value", "Hello World!");
            x.setAttribute("id", y);
            document.body.appendChild(x);
            y = "";
        }else{
            console.log('adios');
        }
    });
});

with this I generate the input and I put the id identical to the checkbox but if I select another checkbox while there is another selected, it takes the id of the first checkbox that was selected. I hope you can support me

    
asked by Jose Luis Ramirez Arambul 12.12.2018 в 23:10
source

1 answer

0

Instead of selecting the checked input, use this like this:

 $(function() {
$("input[type='checkbox']").click(function() {
    if ($(this).is(':checked') ) {
        var y = $(this).attr("id");
        var x = document.createElement("INPUT");
        x.setAttribute("type", "text");
        x.setAttribute("value", "Hello World!");
        x.setAttribute("id", y);
        document.body.appendChild(x);
        y = "";
    }else{
        console.log('adios');
    }
});
});
    
answered by 12.12.2018 / 23:12
source