首页 > 解决方案 > jquery ajax modal 问题触发验证和提交处理程序

问题描述

认为我迷失在我的代码中......无法找出问题所在。我有一个模式可以打开不同的表单,在表单上设置名称和 id 并相应地提交按钮,但是按下提交按钮时没有任何反应。我的 javascript 知识是有限的,并且基于尝试和失败、尝试和失败、尝试,有时会取得结果:)

回到这里的问题......模式打开正常但是点击提交时没有任何反应......至少对我来说没有任何可见......

希望我已经解释了我的问题。

这称为模态

<span class="stedModal" data-type="sted" title="Legg til sted" style="cursor: pointer"> <i class="fas fa-plus"></i></span>

模态:

    <!-- Modal - Legg til sted -->
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">

        <!-- Modal content-->
        
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Legg til sted</h4>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
<!-- name and id is set to sendStedForm in the script that calls the modal -->
                <form action="javascript: void(0)" name="none" id="none" class="modalForm">
                    <div class="main"></div>
<!-- addSted.php is inserted here -->
                    <div class="text-end"> 
<!-- button name and id is set by the script that calls the modal to submitSted -->
                        <button type="submit" name="none1" id="none1" class="btn btn-sm btn-info submitButton" ><i class="far fa-trash-alt"></i> Lagre</button>
                        <button type="button" class="btn btn-sm btn-success" data-bs-dismiss="modal" aria-label="Close"><i class="fas fa-times"></i> Lukk</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

调用 addSted.php

 <input type="hidden" name="lag_id" id="slag_id" value="<?= session()->get('lag_id'); ?>">
    <div class="container">
        <div class="row">
            <div class="col">
                <div class="form-group">
                    <label for="sted">Sted<span class="text-danger fw-bold">*</span></label>
                    <input type="text" name="sted" id="ssted" class="form-control required" placeholder="Sted">
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <div class="form-group">
                    <label for="oppmote">Oppmøte<span class="text-danger fw-bold">*</span></label>
                    <input type="text" name="oppmote" id="soppmote" class="form-control" placeholder="Oppmøtested">
                </div>
            </div>
        </div>
        <div class="row mb-3">
            <div class="col">
                <div class="form-group">
                    <label for="sted">Oppmøte tid<span class="text-danger fw-bold">*</span><small class="text-muted">Timer før oppdrag starter</small></label>
                    <input type="text" name="oppmote_tid" id="soppmote_tid" class="form-control" placeholder="Oppmøte tid">
                </div>
            </div>
        </div>
    </div>

脚本

<script>

function goBack() {
  window.history.back();
}

$('#alert').hide();

$('.stedModal').click(function() {
    var typet = $(this).data('type');

    if (typet == 'type') {
        var url = '/vakter/ajaxAddType';
        $('.modalForm').attr('id', 'sendTypeForm');
        $('.modalForm').attr('name', 'sendTypeForm');
        $('.submitButton').attr('id', 'submitType');
        $('.submitButton').attr('name', 'submitType');
        $('.modal-title').html('Legg til Type');


    } else if (typet == 'sted') {
        var url = '/vakter/ajaxAddSted';
        $('.modalForm').attr('id', 'sendStedForm');
        $('.modalForm').attr('name', 'sendStedForm');
        $('.submitButton').attr('id', 'submitSted');
        $('.submitButton').attr('name', 'submitSted');
        $('.modal-title').html('Legg til Sted');
    }

    // AJAX request
    $.ajax({
        url: url,
        type: 'post',
        success: function(response){ 
            // Add response in Modal body
            $('#alert').hide();

            $('.main').html(response);
            
            // Display Modal
            $('#Modal').modal('show'); 
        }
    });
});


if ($("#sendStedForm").length > 0) {

    $("#sendStedForm").validate({
        rules: {
            sted: {
                required: true,
                maxlength: 100,
            },
            oppmote: {
                required: true,
                maxlength: 100,
            }, 
            oppmote_tid: {
                pattern: /^[0-9,]+$/,
                maxlength: 4,
            }
        },
        messages: {
            sted: {
                required: "<small class=\"text-danger\">Legg inn sted</small>",
                maxlength: "<small class=\"text-danger\">Sted bør ikke være så langt. 100 tegn er maks</small>",
            },
            oppmote: {
                required: "<small class=\"text-danger\">Legg inn en kort beskrivelse</small>",
                maxlength: "Beskrivelsen bær ikke være så lang. Maks 100 tegn</small>",
            },  
            oppmote_tid:  {
                pattern: "<small class=\"text-danger\">Skriv inn ett gyldig nr</small>",
                maxlength: "<small class=\"text-danger\">Oppmøte tid er for langt. Maks 3 tegn</small>",
            },
        },
        submitHandler: function(form) {
            alert('hi');
            $('#submitSted').html('lagrer..');
            // var lag_id = $("#slag_id").val();  
            // var sted = $("#ssted").val();  
            // var oppmote = $("#soppmote").val();  
            // var oppmote_tid = $("#soppmote_tid").val(); 
            // if (!oppmote_tid) { oppmote_tid = '0';}
            // oppmote_tid = oppmote_tid.replace(/,/g, '.');
            $.ajax({
                url: "<?php echo base_url('/vakter/ajaxAddSted/post') ?>",
                type: "POST",
                // data: $('#ajax_form').serialize(),
                dataType: "json",
                // data: { lag_id : lag_id, sted : sted, oppmote : oppmote, oppmote_tid : oppmote_tid },
                data: $('#sendStedForm').serialize(),
                success: function( response ) {
                    console.log(response);
                    console.log(response.success);
                    $('#submitSted').html('Submit');
                    $('#alert').html(response.msg);
                    $('#alert').addClass(response.typemsg);
                    $('#alert').show();
                    // $('#res_message').removeClass('d-none');
                    // document.getElementById("ajax_form").reset(); 
                    // alert("User record updated successfully with ID: "+response.id);  
                    $("#sted").append('<option value="'+ response.id +'">'+ sted + ' - ' + oppmote + ' - ' + oppmote_tid + ' timer</option>')
                    $('#stedModal').modal('hide'); 
                    
                    $('#submitSted').html('<i class="far fa-trash-alt"></i> Lagre');
                    setTimeout(function(){
                        $('#alert').hide();
                        $('#alert').html('');
                    },10000);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                }
            });
        }
    });
}

标签: javascriptjqueryajax

解决方案


尝试将 sendStedForm 包装在一个函数中,并在 dom 实际上具有要使用的 sendStedForm id 之后调用它,该 id 是在加载 ajax 数据并将其放置在 html 中之后。虽然我没有对此进行测试,但我希望这应该有效。

function goBack() {
    window.history.back();
}

$('#alert').hide();

$('.stedModal').click(function() {
    var typet = $(this).data('type');

    if (typet == 'type') {
        var url = '/vakter/ajaxAddType';
        $('.modalForm').attr('id', 'sendTypeForm');
        $('.modalForm').attr('name', 'sendTypeForm');
        $('.submitButton').attr('id', 'submitType');
        $('.submitButton').attr('name', 'submitType');
        $('.modal-title').html('Legg til Type');


    } else if (typet == 'sted') {
        var url = '/vakter/ajaxAddSted';
        $('.modalForm').attr('id', 'sendStedForm');
        $('.modalForm').attr('name', 'sendStedForm');
        $('.submitButton').attr('id', 'submitSted');
        $('.submitButton').attr('name', 'submitSted');
        $('.modal-title').html('Legg til Sted');
    }

    // AJAX request
    $.ajax({
        url: url,
        type: 'post',
        success: function(response){
            // Add response in Modal body
            $('#alert').hide();

            $('.main').html(response);

            // Display Modal
            $('#Modal').modal('show');

            process_sendStedForm();
        }
    });
});


function process_sendStedForm(){
    if ($("#sendStedForm").length > 0) {

        $("#sendStedForm").validate({
            rules: {
                sted: {
                    required: true,
                    maxlength: 100,
                },
                oppmote: {
                    required: true,
                    maxlength: 100,
                },
                oppmote_tid: {
                    pattern: /^[0-9,]+$/,
                    maxlength: 4,
                }
            },
            messages: {
                sted: {
                    required: "<small class=\"text-danger\">Legg inn sted</small>",
                    maxlength: "<small class=\"text-danger\">Sted bør ikke være så langt. 100 tegn er maks</small>",
                },
                oppmote: {
                    required: "<small class=\"text-danger\">Legg inn en kort beskrivelse</small>",
                    maxlength: "Beskrivelsen bær ikke være så lang. Maks 100 tegn</small>",
                },
                oppmote_tid:  {
                    pattern: "<small class=\"text-danger\">Skriv inn ett gyldig nr</small>",
                    maxlength: "<small class=\"text-danger\">Oppmøte tid er for langt. Maks 3 tegn</small>",
                },
            },
            submitHandler: function(form) {
                alert('hi');
                $('#submitSted').html('lagrer..');
                // var lag_id = $("#slag_id").val();
                // var sted = $("#ssted").val();
                // var oppmote = $("#soppmote").val();
                // var oppmote_tid = $("#soppmote_tid").val();
                // if (!oppmote_tid) { oppmote_tid = '0';}
                // oppmote_tid = oppmote_tid.replace(/,/g, '.');
                $.ajax({
                    url: "<?php echo base_url('/vakter/ajaxAddSted/post') ?>",
                    type: "POST",
                    // data: $('#ajax_form').serialize(),
                    dataType: "json",
                    // data: { lag_id : lag_id, sted : sted, oppmote : oppmote, oppmote_tid : oppmote_tid },
                    data: $('#sendStedForm').serialize(),
                    success: function( response ) {
                        console.log(response);
                        console.log(response.success);
                        $('#submitSted').html('Submit');
                        $('#alert').html(response.msg);
                        $('#alert').addClass(response.typemsg);
                        $('#alert').show();
                        // $('#res_message').removeClass('d-none');
                        // document.getElementById("ajax_form").reset();
                        // alert("User record updated successfully with ID: "+response.id);
                        $("#sted").append('<option value="'+ response.id +'">'+ sted + ' - ' + oppmote + ' - ' + oppmote_tid + ' timer</option>')
                        $('#stedModal').modal('hide');

                        $('#submitSted').html('<i class="far fa-trash-alt"></i> Lagre');
                        setTimeout(function(){
                            $('#alert').hide();
                            $('#alert').html('');
                        },10000);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                });
            }
        });
    }
}

推荐阅读