jquery validate does not validate within modal bootstrap

Asked

Viewed 1,165 times

0

I’m having trouble making jquery validate work within the bootstrap modal using a dynamic link (I don’t know if this is the reason). When it is outside it works perfectly more within the same no. follows below the codes:

php document.

        <script src="js/jQuery-2.1.4.min.js"></script>
    <script type="text/javascript" src="js/jquery.validate.min.js"></SCRIPT>
        <script type="text/javascript" src="js/sweetalert.min.js"></SCRIPT>

        <script type="text/javascript" language="javascript">
        $(document).on('click', '[data-toggle="meumodal"]', function(event){
          event.preventDefault();
          target = $(this).attr("data-target");
          content = $(this).attr("href");
          $(target+".modal .modal-content").load(content,function(){
             $(target).modal('show');
          });
        });



        jQuery(document).ready(function() {
            $('#jsontable').DataTable({
                "lengthMenu": [ [5, 25, 50, 100, -1], [5, 25, 50, 100, "Todos"] ],
                "processing": true,
                "serverSide": true,
                "oLanguage": {
                    "sUrl": "busca/pt-br.txt"
                },

                "ajax": "busca/documento_consulta.php"
            });

        });
        </script>

<div class="modal fade" id="myModal" data-toggle="meumodal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

    </div>
   </div>
</div>


<a data-toggle="meumodal" href="documento_devolver.php?id='.$row[9].'" data-target="#myModal" class="btn btn-danger" title="Devolver Requerimento"><i class="fa fa-thumbs-o-down"></i></a>

document_return.php

<script type="text/javascript">
$('#resetForm').on('click', function(){
document.getElementById("devolve").reset();
});

            //form validation rules
            $("#devolve").validate({

                rules: {
                    exigencia: "required" 


                },
                messages: {
                    exigencia: "* Informe o motivo da devolução",
                },
                highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error')
        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
    },
    unhighlight: function (element) {
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
    },
    //errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    },
                submitHandler: function(form) {
                    SalvarRegistro();
                }
            });


function SalvarRegistro(){

            $("#btn_salvar").addClass('bloqueia');
            var dados = jQuery('#devolve').serialize();

            swal({
              title: "Tem Certeza?",
              text: "Deseja Devolver este requerimento!",
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#DD6B55",
              confirmButtonText: "Sim, devolver",
              showLoaderOnConfirm: true,
              closeOnConfirm: false
            },
            function(){
                $.ajax({
                            type: "POST",
                            dataType: "json",
                            url : 'acao/documento_acao.php',
                            data : dados,
                            success: function(data) {
                                $("#btn_salvar").removeClass('bloqueia');
                                if(data.sucesso == 0){
                                    swal({ 
                                title: "Cadastrado!",
                                text: data.msg,
                                type: "success" 
                                },
                                function(){
                                parent.location.href = parent.location.href;
                                });
                                }else{
                                swal({ 
                                title: "Um erro ocorreu",
                                text: data.msg,
                                type: "error" 
                                }); 
                                }
                            }
                        });

                    return false;
            });

    }
</script>
<div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Devolver Documento</h4>
            </div>
            <div class="modal-body">    
        <form action="" method="post" id="devolve">
                    <div class="col-sm-12">
                        <div class="form-group has-feedback">
                            <label for="message-text" class="control-label">Motivo da devolução:</label>
                            <textarea name="exigencia" id="exigencia" class="form-control"></textarea>
                            <span class="form-control-feedback glyphicon"></span>
                        </div>
                    </div>
            </div>
    <div class="modal-footer">


        <input name="usuario_lancamento" id="usuario_lancamento" type="hidden" value="<?php echo $_SESSION['usuarioid']; ?>" />
                    <input name="id_documento" id="id_documento" type="hidden" value="<?php echo $id_documento; ?>" />
                    <input name="action" id="action" type="hidden" value="devolver" />
        <input type="submit" id="btn_salvar" class="btn btn-primary" value="enviar">
        </form>
        <button type="button" class="btn btn-default" id="resetForm">Limpar</button>                   
</div>

From what I could see it seems that the button does not work, because when I write in the field and I click away it says it is filled and if I delete what I wrote it gives error of the empty field. Even with the field filled does not send. I tested by removing the validation and sent.

From now on I appreciate any help.

I put in jsfiddle for better understanding:

https://jsfiddle.net/opeta/bLsvkeot/1/

I did a test with the modal opening completely on the parent page without the external link and it worked more to solve my problem I need the external link.

  • That question here is part of the problem, is it not? After all, what is the reason for carrying the modal out of the page?

  • @Shutupmagda this question is more specific because only jquery validate does not work, each page I call in the modal has a dynamically generated edit link. It seems that the validate works in part when you fill in the field and then delete it. In the solution of that question it would not be possible to use because the links are dynamic. example: documento_devolve.php? id=4

  • You need to open a modal for each different id by passing the ID to the modal, that’s it?

  • exactly the id changes every link. if you repair I just call the validate on the parent page and even then it doesn’t work.

2 answers

1


There are other ways to do it (even more elegant ways) but I think you should test it here:

index php.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js" ></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script>
    $(function () {
        $("a[data-target]").click(function () {
            $('#id_documento').val($(this).attr("data-id"));
            $('#usuario_lancamento').val($('#_usuario_lancamento').val());
            $(':reset').val($(this).attr("data-id"));
        });
        $(":reset").click(function () {
            $('#id_documento').val($(this).val());
            $('#usuario_lancamento').val($('#_usuario_lancamento').val());
        });
    });
        </script>
    </head>
    <body>
        <input type="hidden" id="_usuario_lancamento" value="<?=md5(date('H:i:s'))?>">
        <?php echo file_get_contents('modal.php'); ?>
        <br>
        <div class='container'>
            <a type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id='1'>
              Launch myModal 1
            </a>
            <a type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal" data-id='2'>
              Launch myModal 2
            </a>
        </div>
    </body>
</html>

modal.php

<!-- myModal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <form action='acao/documento_acao.php' method="post" class="modal-content" name="form_myModal" id="form_myModal">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Devolver Documento myModal</h4>
            </div>
            <div class="modal-body">
                <div class="col-sm-12">
                    <div class="form-group has-feedback">
                        <label for="message-text" class="control-label">Motivo da devolucao:</label>
                        <textarea name="exigenciamyModal" id="exigenciamyModal" class="form-control"></textarea>
                        <span class="form-control-feedback glyphicon"></span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <input name="usuario_lancamento" id="usuario_lancamento" type="hidden" value="%usuario_lancamento%"/>
                <input name="id_documento" id="id_documento" type="hidden" value="%id_documento%"/>
                <input name="action" id="action" type="hidden" value="devolver"/>
                <button type="reset" class="btn btn-default">
                    <span class="glyphicon glyphicon-refresh"></span>
                    Limpar
                </button>
                <button id="btn-salvarmyModal" type="submit" class="btn btn-primary">
                    <span class="glyphicon glyphicon-ok-circle"></span>
                    Confirmar
                </button>
            </div>
        </form>
    </div>
</div>
<script>
    //form validation rules
    $("#form_myModal").validate({
        rules: {
            exigenciamyModal: "required"
        },
        messages: {
            exigenciamyModal: "* Informe o motivo da devolucao",
        },
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error')
            $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
            $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
        },
        //errorElement: 'span',
        errorClass: 'help-block',
        errorPlacement: function (error, element) {
            if (element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            $("#btn-salvarmyModal").addClass('bloqueia');
            var dados = jQuery('#form_myModal').serialize();
            alert($("#exigenciamyModal").val());
            form.submit();
        }
    });
</script>

document_acao.php

<?php
foreach ($_POST as $key => $val){
    echo $key.": ".$val."<br>";
}
?>
<br>
<a href="index.php">Home</a>

0

I’ll leave here the solution I found because I needed to recover the values via get or $id = $_GET['id']; which was to create an iframe and call the independent page as I used with Fancy.box in this case it has to be called again jquery and the plugins to be used.

modal page with iframe:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="container">
        <div class="row">
        <div class="col-xs-12">
          <div class="page">

    <button type="button" class="modalButton" data-toggle="modal" data-src="modal.php?id=1" data-width="700" data-height="500" data-target="#myModal">Abrir modal</button>
       </div>
        </div>
      </div>
      </div>


    <div class="modal fade" id="myModal">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-body">

          <div class="close-button">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          </div>
          <div class="embed-responsive embed-responsive-16by9">
                                <iframe class="embed-responsive-item" frameborder="0"></iframe>
          </div>
                </div>

            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

<script>
( function($) {

function iframeModalOpen(){

        // impostiamo gli attributi da aggiungere all'iframe es: data-src andrà ad impostare l'url dell'iframe
        $('.modalButton').on('click', function(e) {
            var src = $(this).attr('data-src');
            var width = $(this).attr('data-width') || 800; // larghezza dell'iframe se non impostato usa 640
            var height = $(this).attr('data-height') || 600; // altezza dell'iframe se non impostato usa 360

            // stampiamo i nostri dati nell'iframe
            $("#myModal iframe").attr({
                'src': src,
                'height': height,
                'width': width
            });
        });

        // se si chiude la modale resettiamo i dati dell'iframe per impedire ad un video di continuare a riprodursi anche quando la modale è chiusa
        $('#myModal').on('hidden.bs.modal', function(){
            $(this).find('iframe').html("");
            $(this).find('iframe').attr("src", "");
        });
    }

  $(document).ready(function(){
        iframeModalOpen();
  });

  } ) ( jQuery );
</script>

standalone page, note that I only used the bootstrap form then having to call the css from it.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js" ></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<form action='acao/documento_acao.php' method="post" name="form_myModal" id="form_myModal">

                <h4 class="modal-title">Dynamic Content </h4>


            <div class="modal-body">
                <div class="col-sm-12">
                    <div class="form-group has-feedback">
                        <label for="message-text" class="control-label">Motivo da devolucao:</label>
                        <textarea name="exigenciamyModal" id="exigenciamyModal" class="form-control"></textarea>
                        <span class="form-control-feedback glyphicon"></span>
                    </div>
                </div>
            </div>


                <input name="usuario_lancamento" id="usuario_lancamento" type="hidden" value="%usuario_lancamento%"/>
                <input name="id_documento" id="id_documento" type="hidden" value="%id_documento%"/>
                <input name="action" id="action" type="hidden" value="devolver"/>
                <button type="reset" class="btn btn-default">
                    <span class="glyphicon glyphicon-refresh"></span>
                    Limpar
                </button>
                <button id="btn-salvarmyModal" type="submit" class="btn btn-primary">
                    <span class="glyphicon glyphicon-ok-circle"></span>
                    Confirmar
                </button>

            </form>

<script>
 //form validation rules
    $("#form_myModal").validate({
        rules: {
            exigenciamyModal: "required"
        },
        messages: {
            exigenciamyModal: "* Informe o motivo da devolucao",
        },
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error')
            $(element).parent().find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove');
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
            $(element).parent().find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok');
        },
        //errorElement: 'span',
        errorClass: 'help-block',
        errorPlacement: function (error, element) {
            if (element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        },
        submitHandler: function(form) {
            $("#btn-salvarmyModal").addClass('bloqueia');
            var dados = jQuery('#form_myModal').serialize();
            alert($("#exigenciamyModal").val());
            form.submit();
        }
    });
</script> 

Browser other questions tagged

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