Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

jquery - Replacing text on div

I have a form that if I select certain values from a <select> and <input>, the jquery goes in action.

I have the following div:

<div class="alert alert-info"  role="alert">
    <div id="holders_1_contracts">
        Contratos deste Titular: &nbsp; <i class="fal fa-spinner fa-spin-2x"></i>
    </div>
</div>

If the <select id="holders_1_partner_type_id"> changed, this enter in action:

$('#holders_1_partner_type_id').change(function()
{
    $("#holders_1_contracts").replaceWith('Contratos deste Titular: &nbsp; <i class="fal fa-spinner fa-spin-2x"></i>');
});

If the <input id="holders_1_partner_nr", changes, this enter in action:

$('#holders_1_partner_nr').change(function()
{
    let partner_type_id = $("#holders_1_partner_type_id").val();
    let partner_nr = $("#holders_1_partner_nr").val();

    switch(partner_type_id) {
        case '2':
            $.ajax({
                url: '...',
                type: 'get',
                data: {
                ..
                },
                success: function(response)
                {
                    let data = JSON.parse(response);

                    if (data.success !== false) {
                        Swal.fire({
                            icon: 'success',
                            title: 'OCC Encontrado!',
                            text: 'Os campos foram pré-preenchidos. Valide os dados antes de avan?ar.',
                            showConfirmButton: true,
                            allowOutsideClick: true,
                        });

                        $("#holders_1_contracts").replaceWith(data.contracts);

                    } else {
                        Swal.fire({
                            ...
                        });
                    }
                },
            });
            break;

        default:
            break;
    }
});

Basically, if the user enters the holders_1_partner_nr (number), the application loads the contract numbers from the database. If the holders_1_partner_type_id changes, the jquery should replace all loaded contracts with a text and a spinner.

The fact is, this code only works 1 time, If I load the contracts 1 time.

What am I doing wrong? My jquery/js skills aren't really the best.

Regards and Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In each case, you're replacing/removing the element the event lister is attached to.

Please change:

.replaceWith( ..... );

To:

.html( ..... );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...