vincent15000
2 months ago

Form and jQuery

Posted 2 months ago by vincent15000

Hello,

I have a form for some drawings with different fields, some fields are relations with other tables, for example I have a select named substrate_id.

In the form, near the select, I have a + button to open a modal window to add a new substrate if the one I need is not already in the list.

What I want to do is to add a new substrate via the modal form and then reload only the select and automatically select the substrate I just added.

Here is my code, but I think there s a better way to do the same.

$("#buttonAddSubstrate").on('click', function(e) {
    e.preventDefault();
    $.get(
        $(this).attr("url"),
    )
    .done(function(data) {
        $(".modal-content").html(data);
        $("#modalSubmit").on("click", function(e) {
            e.preventDefault();
            $.post(
                $("#addSubstrateForm").attr("action"),
                {
                    "_token": $("[name='_token']").val(),
                    "title": $("#addSubstrateForm").find("[name='title']").val(),
                },
            )
            .done(function(data) {
                alert($("#addSubstrateForm").find("[name='route']").val());
                $.get(
                    $("#addSubstrateForm").find("[name='route']").val(),
                )
                .done(function(data) {
                    $("[name='substrate_id']").replaceWith(data);
                    $("#modalAddSubstrate").modal("hide");
                });
            })
            .fail(function() {
                $("#addSubstrateForm").find("[name='title']").addClass("is-invalid");
            });
        });
        $("#modalAddSubstrate").modal("show");
    });
});

Thanks for your ideas to improve this code if it is possible.

Please sign in or create an account to participate in this conversation.