How to change elements dynamically through Checkbox?

Asked

Viewed 807 times

1

Guys I have a problem where I need to make a function with parameters aiming if a checkbox is marked or not. I managed to make for another field, but this was static, now I need to make for elements that will be dynamically added via a button. The point is, I have in my DIV "products" a product name field, where this by default comes with a <select>populated with products already registered in the BD through jQuery and PHP and below a checkbox to mark if the product is not registered, and when marked, appears an input field in place of select to enter the name of the Product. How can I do this, aiming that other product Divs can be added by the user by clicking on the add button and that, each checkbox marked should just disappear with the select and show the input in its own field ?

index php.:


                <div class="container" id="produtos">
                    <div class="separator"></div>

                    <div class="title-padrao">
                        <h1 class="text-center">
                            Produtos
                        </h1>
                    </div>

                    <div id="allProducts">
                        <div class="produtos-wrap" name="produtos-wrap"> <!---- DIV A SER CLONADA / ADICIONADA !---->
                            <div class=" text-center select_height primeira">
                                <b>Item:</b>
                                <br>
                                <input type="text" class="index font-pop input-div" id="index_produto"
                                       name="index_produto[]" value="1" readonly="true">
                            </div>

                            <div class="text-center select_height segunda">
                                <b>ID:</b>
                                <br>
                                <input class="font-pop number_id_produto input-div" value="0" readonly="true"
                                       name="id_produto[]">
                            </div>

                            <div class="select-produto select_height terceira">
                                <b>Selecione um produto:</b>
                                <select class="selectpicker form-control" data-show-subtext="false"
                                        data-live-search="true" name="select_produtos[]" id="select_produtos"
                                        onchange="initProdutos(this)">
                                    <?php

                                    echo '<option disabled selected hidden value="Selecione um produto..." data-subtext="Selecione um produto...">Selecione um produto...</option>';

                                    foreach ($result2 as $item_produtos) {
                                        echo '<option data-subtext="' . $item_produtos['desc_produto'] . '" value="'
                                            . $item_produtos['desc_produto'] . '">' . $item_produtos['desc_produto'] . '</option>';
                                    }
                                    ?>
                                </select>
                                <input type="text" class="" name="produto_new_input" id="produto_new_input"
                                   style="display: none">
                                <input type="checkbox" id="change_produto" name="change_produto[]"
                                   value="Fornecedor não cadastrado">&nbsp;
                                <label for="change_produto" id="checkbox-produto-text">Produto não cadastrado</label>

                            </div>

                            <div class="text-center select_height quarta">
                                <b>Embalagem:</b>
                                <br>
                                <input type="text" maxlength="2" class="edit-input font-pop" name="embalagem[]"
                                       value="">
                            </div>

                            <div class="text-center select_height quinta">
                                <b>Preço:</b>
                                <br>
                                <input type="number" id="preco-input" name="preco[]"
                                       oninput="this.value = Math.abs(this.value)" min="0" class="edit-input font-pop"
                                       value="0">
                            </div>

                            <div class="text-center select_height sexta">
                                <b>Quantidade:</b>
                                <br>
                                <input type="number" id="qtd-input" oninput="this.value = Math.abs(this.value)" min="0"
                                       class="edit-input font-pop"
                                       value="0" name="quantidade-produto[]">
                            </div>

                            <div class="text-center select_height text-right setima">
                                <b>Preço do Produto:</b>
                                <br>
                                <input class="font-pop preco-produto input-div" readonly="true" name="preco-produto[]">
                            </div>

                            <div class="text-center select_height oitava" id="div-remove">
                                <button type="button"
                                        class="remover glyphicon glyphicon-remove button-produto"></button>
                            </div>
                        </div>
                    </div>
                    <button type="button" id="add-button" class="glyphicon glyphicon-plus-sign button-produto"></button>
                </div>

Jquery function:

$(document).ready(function() {
    $("[name='change_produto[]']").on('change', function(){
        if($(this).is(':checked')) {
            $("div.btn-group.bootstrap-select.form-control").children().eq(0).css("display", "none");
            $("#produto_new_input").css("display", "block");
        } else {
            $("div.btn-group.bootstrap-select.form-control").children().eq(0).css("display", "block");
            $("#produto_new_input").css("display", "none");
        }
    })
})

NOTE: This field that I have set in Jquery is the only one that actually disappears with SELECT, because it is the same that appears as full field in Inspect Element, as shown in the following image: inserir a descrição da imagem aqui

Clone function():

$(document).ready(function () {
    var clone = $('#allProducts').html().replace(/<b>.*?<\/b>|<br>/g, "");
    $(document).on('click', '#add-button', addProd);

    $(document).on('click', '.remover', function () {
        $(this).parents('.produtos-wrap').remove();
        ids();
        calculos();
    });

    function addProd() {
        $('#allProducts').append(clone);
        ids();
        $(".produtos-wrap[i]").addClass("p-all");
    }

    function ids() {
        $("[name='index_produto[]']").each(function (i, e) {
            $(e).val(i + 1);
        });
    }
});

Post-Edit:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • 1

    Try changing to $(document).on('change', '[name="change_produto[]"]', function(){

  • It didn’t work @Sam, before he was enabling Input but giving display:None on another element; now he’s not doing either.

  • But vc is cloning objects and repeating id’s. It will not work with id’s because an id cannot be repeated.

1 answer

1


You are cloning a div that has some elements with id’s. An id cannot be repeated on the same page. For example, in the case of the checkbox label where the attribute for reference to the checkbox id, it won’t work on the cloned elements because it will always reference the first checkbox id. When cloning the div, you should create a dynamic id for each checkbox and on for of the Abels. Well, this is something that should be fixed.

Also the name of the inputs that will replace the selects should also be in array form since they can be several, ie instead of name="produto_new_input" should be name="produto_new_input[]".

Regarding showing/hiding select and input when checking the checkbox, the code below does so with dynamic elements. Just fetch the elements from the parent div. No need to use id’s for this:

$(document).ready(function() {
    $(document).on('change', "[name='change_produto[]']", function(){

       var sel = $(this).closest("div").find(".bootstrap-select");

        if($(this).is(':checked')) {
            $(this)
            .closest("div")
            .find(sel.length ? ".bootstrap-select" : "select")
            .hide()
            .end()
            .find("[name='produto_new_input[]']")
            .show();
        } else {
            $(this)
            .closest("div")
            .find(sel.length ? ".bootstrap-select" : "select")
            .show()
            .end()
            .find("[name='produto_new_input[]']")
            .hide();
        }
    })
});
  • this solution is working for the DIV’s that are added, but for the first one that already comes from default does not work due to the Bootstrap class. How can I solve this ? I will edit the question with the images.

  • Ready @Sam, I edited the question with the same.

  • 1

    Change that line: .closest("div") for .closest("div.select-produto")

  • I changed and didn’t change @Sam, I’m going to test by putting the Bootstrap class.

  • At first it worked, but when unchecking the checkbox, it keeps bugging. I edited the question again with the images.

  • 1

    I edited the answer again.

  • 1

    Now it worked out, thank you very much @Sam !!!!

  • Sam I’m sorry for the inconvenience and even the time I took to come talk about, but is there any way I can also change the value of the product ID field when I check / uncheck the checkbox ? I need to change the value of it for some reasons that have arisen here. I tried to do following the same logic of the inputs, but it did not work.

  • You want to change the text in the ID column?

  • Yes, in the case of the <input class="font-pop number_id_produto input-div" value="0" readonly="true" name="id_produto[]">. If the checkbox is marked I want to put a number, and if you uncheck it goes back to 0, for example.

  • Try adding .end().find(".number_id_produto").val(número que vc quer)

  • I tried and it didn’t work Sam. With this form I had even tried before alone but it didn’t work.

  • Try by name: .end().find("[name='id_produto[]']").val(número que vc quer)

  • will look like this: https://jsfiddle.net/9r8osnw7/

  • I tested it here and it didn’t work either, it doesn’t change the field.

  • 1
Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.