jquery validate not valid within modal bootstrap

0

I'm having trouble making jquery validate work within the bootstrap modal using a dynamic link (I do not know if this is the reason). When it is out it works perfectly more inside the same not. below the codes:

document.php

        <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_devolver.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 noticed it seems that the button does not work, because when I write in the field and give a click outside it says it is filled and if I delete what I wrote it gives error of the empty field. Even with the filled field does not send. I tested it by removing the validation and sent it.

Thanks in advance for any help.

I put it in jsfiddle for better understanding:

link

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

    
asked by anonymous 25.11.2016 / 12:26

2 answers

1

There are other ways to do (more elegant ways, too) but I think you should test this 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><scriptsrc="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>

documento_acao.php

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

I'll leave here the solution I found because I needed to retrieve the values via get or be $ id = $ _GET ['id']; which was to create an iframe and call the standalone page as I used it with fancy.box in this case you have to call again the jquery and plugins to use.

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>

<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><scriptsrc="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> 
    
28.11.2016 / 12:35