Make jQuery validator validate hidden inputs on submit

I have a button like

<button onclick="$('#myForm').submit()>Submit!</button>

which validates all inputs and submits if validated. I have one hidden input that I want validated as well. The inputs inside the form are all validated whenever their value changes, too. What I want to set the validator to validate hidden inputs.

All the examples I see on the internet are like

$("#myform").validate({
   ignore: ":hidden"
});

which invokes the validation which is what I don't want. I want to define what happens whenever it is invoked. Does that make sense?

  • destroy or reset image croppie

    I have two different section for uploading image in the website, one of them for banner and another one for profile picture. They have different dimension as well. uploading image works in a overlay page.

    I added image croppie in my server and according in my codes, when the user click on the banner image, it's automatically set its dimension to image croppie and when the user click on the profile picture, it set the profile picture size to image croppie.

    All i want is, when user upload a photo and then cancel it, everything will be gone. Now if user upload a photo in banner photo, and then cancel it, the photo is still available when we come back to the overlay of uploading image. Also if user click on the profile picture, it shows the photo of the banner with its dimension again.

    i want that when user clicks on cancel button (which is .fa-times in my codes), everything about the uploaded image and its dimension will be removed. Then if user click on the another section (profile photo or banner), the user see a fresh page with the right dimension.

    Here is my codes, this is the codes, when user clicks on the browse button to select the image for uploading.

    this.body.addClass("overlay--active");
    var imageBody = $(e.target).closest(".icon");
    this.height = imageBody.attr("data-height");
    this.width = imageBody.attr("data-width");
    
    
    var crop = new Croppie(document.getElementById('js-image-editor'), {
        enableExif: true,
        showZoomer: true,
        viewport: { width: this.width, height: this.height, type: 'square'},
        boundary: { width: this.width, height: this.height}
    });
    
        function readFile(input) {
          if (input.files && input.files[0]) {
                  var reader = new FileReader();
    
                  reader.onload = function (e) {
              $('.section').addClass('ready');
                    // crop.croppie('bind', {
                    crop.bind({
                      url: e.target.result
                    }).then(function(){
                      console.log('jQuery bind complete');
                    });
    
                  }
    
                  reader.readAsDataURL(input.files[0]);
              }
              else {
                swal("Sorry - you're browser doesn't support the FileReader API");
            }
        }
    
    
        $('.button-upload-image').on('change', function () { readFile(this); });
    
    
    
        $('.fa-save').on('click', function (ev) {
           crop.result ({
            type: 'canvas',
            size: 'viewport'
          }).then(function () {
            console.log('upload image complete');
          });
        });
    
    
        $(".fa-times").click(function() {
          $('.section').removeClass('ready');
          crop.bind ({
            url: ''
          }).then(function(){
            console.log('reset complete');
          });
        })
    

    as you can see in the last block, i tried to reset image croppie, but it's not working. Every time the error of "Croppie: Can't initialize croppie more than once" come up.

    Anyone can help me on this? i really appreciate for your help in advance.

  • Codeigniter doesnt upload any image

    I create customer edit page. I can edit everything on input text. But I only cant upload any photo to directory and database. How can I do for this? I try more things. This code's upload photo works best when I add customer. But I can not edit photo upload again for customers. I need your helps. Thank you all.

    Controller:

    public function update($cusId) {
            $maxDim = 100;
            $file_name = $_FILES['cosImg']['tmp_name'];
            list($width, $height, $type, $attr) = getimagesize( $file_name );
            if ( $width > $maxDim || $height > $maxDim ) {
                $target_filename = $file_name;
                $ratio = $width/$height;
                if( $ratio > 1) {
                    $new_width = $maxDim;
                    $new_height = $maxDim/$ratio;
                } else {
                    $new_width = $maxDim*$ratio;
                    $new_height = $maxDim;
                }
                $src = imagecreatefromstring( file_get_contents( $file_name ) );
                $dst = imagecreatetruecolor( $new_width, $new_height );
                imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
                imagedestroy( $src );
                imagepng( $dst, $target_filename ); // adjust format as needed
                imagedestroy( $dst );
            }
    
            if (isset($_FILES) && $_FILES['cosImg']['error'] == '0') {
                $config['upload_path'] = './upload/customer';
                $config['allowed_types'] = 'jpeg|jpg|png|gif';
                $config['max_size']             = 1024;
                $config['max_width']            = 1000;
                $config['max_height']           = 1000;
                $config['overwrite'] = TRUE;
                $new_name = $this->input->post("cosUserName");
                $config['file_name'] = $new_name;
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if ( ! $this->upload->do_upload('cosImg'))
                {
                    $error = array('error' => $this->upload->display_errors());
                    echo json_encode($error);
                }
                else{
                    $upload_data = $this->upload->data();
                    $data = array (
                        "cosCode" => $this->input->post("cosCode"),
                        "cosUserName" => $this->input->post("cosUserName"),
                        "cosPassword" => $this->input->post("cosPassword"),
                        "cosEmail" => $this->input->post("cosEmail"),
                        "cosName" => $this->input->post("cosName"),
                        "cosSurname" => strtoupper($this->input->post("cosSurname")),
                        "cosImg" => $upload_data['file_name'],
                        "cosLang" => $this->input->post("cosLang"),
                        "cosStatus" => $this->input->post("cosStatus"),
                        "cosEditDate" => date('Y-m-d H:i:s'),
                    );
                    $update = $this->db->where("cusId", $cusId)->update("customer", $data);
                    if($update) {
                        redirect(base_url("customers"));
                    }else {
                        echo "Hata!";
                    }
                }
            }
            else{
                $data = array (
                    "cosCode" => $this->input->post("cosCode"),
                    "cosUserName" => $this->input->post("cosUserName"),
                    "cosPassword" => $this->input->post("cosPassword"),
                    "cosEmail" => $this->input->post("cosEmail"),
                    "cosName" => $this->input->post("cosName"),
                    "cosSurname" => strtoupper($this->input->post("cosSurname")),
                    "cosLang" => $this->input->post("cosLang"),
                    "cosStatus" => $this->input->post("cosStatus"),
                    "cosEditDate" => date('Y-m-d H:i:s'),
                );
                $update = $this->db->where("cusId", $cusId)->update("customer", $data);
                if($update) {
                    redirect(base_url("customers"));
                }else {
                    echo "Hata!";
                }
            }
        }
    

    This is my controller and I can edit everything good. But I can not upload an image. Here my view:

    <form class="cmxform form-horizontal tasi-form" id="signupForm" enctype="multipart/form-data" method="post" action="<?php echo base_url("customers/update/$customer->cusId"); ?>">
                                    <div class="form-group last">
                                        <label class="control-label col-md-3">Avatar Upload:</label>
                                        <div class="col-md-9">
                                            <div class="fileupload fileupload-new" data-provides="fileupload">
                                                <div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
                                                    <img src="<?php echo base_url().'upload/customer/'.$customer->cosImg; ?>" />
                                                </div>
                                                <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>
                                                <div>
                                                       <span class="btn btn-white btn-file">
                                                       <span class="fileupload-new"><i class="fa fa-paper-clip"></i> Select image</span>
                                                       <span class="fileupload-exists"><i class="fa fa-undo"></i> Change</span>
                                                       <input type="file" class="default" name="userImg" accept="image/gif, image/jpeg, image/png, image/png" />
                                                       </span>
                                                </div>
                                            </div>
                                            <span class="label label-danger">NOTE!</span>
                                            <span>
                                                 Please Upload Your Profile Photo!
                                            </span>
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="username" class="control-label col-lg-2">Customer Code <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class=" form-control" id="username" name="cosCode" type="text" value="<?php echo $customer->cosCode; ?>" />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="username" class="control-label col-lg-2">Username <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class=" form-control" id="username" name="cosUserName" type="text" value="<?php echo $customer->cosUserName; ?>" />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="password" class="control-label col-lg-2">Password <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class="form-control " id="password" name="cosPassword" type="password" value="<?php echo $customer->cosPassword; ?>" readonly />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="email" class="control-label col-lg-2">E-Mail <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class="form-control " id="email" name="cosEmail" type="email" value="<?php echo $customer->cosEmail; ?>" />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="firstname" class="control-label col-lg-2">First Name <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class=" form-control" id="firstname" name="cosName" type="text" value="<?php echo $customer->cosName; ?>" />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="lastname" class="control-label col-lg-2">Last Name <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class="form-control " id="lastname" name="cosSurname" type="text" value="<?php echo $customer->cosSurname; ?>" />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="email" class="control-label col-lg-2">Phone <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class="form-control " id="email" name="cosPho" type="phone" value="<?php echo $customer->cosPho; ?>" />
                                        </div>
                                    </div>
                                    <div class="form-group ">
                                        <label for="firstname" class="control-label col-lg-2">Mobile Phone <span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class=" form-control" id="firstname" name="cosGsm" type="phone" value="<?php echo $customer->cosGsm; ?>" />
                                        </div>
                                    </div>
    
                                    <div class="form-group " hidden>
                                        <label for="firstname" class="control-label col-lg-2"><span class="text-danger">*</span></label>
                                        <div class="col-lg-10">
                                            <input class=" form-control" id="firstname" name="cosEditDate" type="phone" value="<?php echo $customer->cosGsm; ?>" />
                                        </div>
                                    </div>
    
                                    <!-- Basic select -->
                                    <div class="form-group">
                                        <label class="control-label col-lg-3">Choose Language <span class="text-danger">*</span></label>
                                        <div class="col-lg-9">
                                            <select name="cosLang" class="form-control">
                                                <option value="<?php echo $customer->cosLang; ?>"><?php echo $customer->cosLang; ?></option>
                                                <option value="en">English</option>
                                                <option value="ar">Arabic</option>
                                            </select>
                                        </div>
                                    </div>
                                    <!-- /basic select -->
    
                                    <!-- Basic select -->
                                    <div class="form-group">
                                        <label class="control-label col-lg-3">Status <span class="text-danger">*</span></label>
                                        <div class="col-lg-9">
                                            <select name="cosStatus" class="form-control">
                                                <option value="<?php echo $customer->cosStatus; ?>"><?php echo $customer->cosStatus; ?></option>
                                                <option value="1">Active</option>
                                                <option value="0">Deactive</option>
                                            </select>
                                        </div>
                                    </div>
                                    <!-- /basic select -->
                                    <div class="form-group">
                                        <div class="col-lg-offset-2 col-lg-10">
                                            <button class="btn btn-success" type="submit" value="Upload">Edit User</button>
                                            <button class="btn btn-default" type="reset">Reset</button>
                                            <button class="btn btn-danger" type="cancel">Cancel</button>
                                        </div>
                                    </div>
                                </form>
    
  • Center Bootstrap Contact Form

    I'm setting up a contact form and I want this form to be centered on my page. But I don't want the full width (col-md-12) of the page. I only want the width of a col-md-6 at the center of the page. Problem is that because I select col-md-6, the form display on the left hand side of the page. How can I center it?

    HTML:

    <div class="container">
        <div class="row">
            <div class="col-md">
                <form action="contact" method="post"> {{--action = where the data must go--}}
    
                    <div class="form-group">
                        <label for="name">Name:</label>
                        <input type="text" class="form-control" id="name" placeholder="Your Name">
                    </div>
                    <div class="form-group">
                        <label for="email">Email address:</label>
                        <input type="email" class="form-control" id="email" placeholder="name@example.com">
                    </div>
                    <div class="form-group">
                        <label for="mobile">Mobile Nr:</label>
                        <input type="email" class="form-control" id="mobile" placeholder="Mobile Nr should start with 08, 07 or 06">
                    </div>
                    <div class="form-group">
                        <label for="message">Your message...</label>
                        <textarea class="form-control" id="message" rows="3"></textarea>
                    </div>
    
                </form>
            </div>
        </div>
    </div>
    
  • How can I style DOM after invalid input?

    I need a help in a task. I have to change color of text, border of form and append new paragraph after typed email is invalid. I wrote a code like that in JS :

    $(document).ready(function () {
        if ($("#mail").is(':invalid')) {
            $("#mail_label").css('color', 'red');
            $("#mail").css('border', '1px solid red');
            var para = document.createElement("p");
            var node = document.createTextNode("Invalid email address");
            para.appendChild(node);
    
            var element = document.getElementById("new_paragraph");
            element.appendChild(para);
            para.setAttribute('id', 'new_text');
            $("#new_text").css({'color': 'red', 'text-align': 'right', 'margin-right': '5%', 'font-size': '12px'});
        };
    });
    

    It is styling my DOM as I wish but from the start because my placeholder is "Enter your email address". I want it to style after invalid input. How can I make it happen?

    If I change placeholder to for example xy@xy.com my site have normal styling. But when I puts in invalid mail the code don't run.

    Can you please help me? It is very important for me cause this is my internship recruitment task.

  • jQuery validate image resolution before upload is not correct

    I want to validate my image height and width with jQuery validation. I have next code:

      <input type="file" name="FacebookImage" class="input-width-hundred-percent" data-val="true" data-rule-imagevalidationsize="true" data-rule-image-imageFacebookResolution="true" id="FacebookImage" />
    

    My script

      $.validator.addMethod("data-rule-imageFacebookResolution", function (value , elem , attrValue) {
                    var reader = new FileReader();
    
                    //Read the contents of Image File.
                    reader.readAsDataURL(elem.files[0]);
                    reader.onload = function (e) {
                        //Initiate the JavaScript Image object.
                        var image = new Image();
    
                        //Set the Base64 string return from FileReader as source.
                        image.src = e.target.result;
    
                        //Validate the File Height and Width.
                        image.onload = function () {
                            var height = this.height;
                            var width = this.width;
                            if (height < 290 || width < 520) {
                                return false;
                            }
                            return true;
                        };
                    }
                    return false;
                }, "Min resolution must be 520 x 290");
    

    UPDATE: (to validate a form I use next)

     $("#socialShareSaveBtn").click(function () {
                var form = $("#share_settings");
                form.validate();
                if (form.valid()) {
                    var data = new FormData(document.getElementById('share_settings'));
                    $.ajax({
                        url: '@Url.Action(MVC.Product.SocialShareEdit())',
                        type: "POST",
                        data: data,
                        processData: false,
                        contentType: false,
                        success: function () {
                            $("#socialShare").modal('hide');
                            $.ajax({
                                url: '@Url.Action(MVC.Product.SocialShareIconsPartial(Model.DeliveryType))',
                                type: "POST",
                                processData: false,
                                contentType: false,
                                success: function (message) {
                                    $("#shareIcons").html(message);
                                }
                            });
                        }
                    });
                }
                });
    

    But I have a problem. When I upload image with correct resolution I also get validation error message. Also when I debug It , It can't enter in reader.onload function. What's wrong here with my code logic? Maybe It's incorrect with "return"? Thanks

  • jQuery Validate not working properly inside PHP

    I'm trying to validade input fields of a form that is contained inside an PHP echo statement using jQuery Validate but nothing happens. Here is the code:

    else {
        echo 
             '<form method="post" class="cmxform" id="cadastraAtividade" action="/?action=cadastrar_ativ_ext&sub_action=gravar_banco">
                <div>
                    <label>Nome da Atividade:</label><br />
                    <input type="text" size="50" id="nome" name="cac_atividade_nome" value=""/>
                 </div>
    
                 <div>
                    <label>Data:</label>
                    <script>DateInput("cac_atividade_data", true, "YYYY/MM/DD")</script>
                </div>
    
                <div>
                    <label>Início:</label><input id="time1" type="time" name="cac_atividade_inicio" value="" required/>
                    <label>Finalização:</label> <input id="time2" type="time" name="cac_atividade_final" value="" required/><br />
                </div>
    
                <div>
                    <label>Descrição:</label><br /><textarea name="cac_atividade_descricao" rows="10" cols="60" minlength=10 required></textarea></div><div>
                    <input class="submit" type="submit" id="botao" value="Submit"/>
                 </div>
             </form>
    
             <script src="js/jquery.min.js"></script>
             <script src="js/jquery.validate.js"></script>
    
             <script>
             $(#"cadastraAtividade").validate(
             {
                rules: {
                    nome: {
                        required: true,
                        minlength: 10
                    }
                }
            });
             </script>';
    }
    

    I've only written one rule and I'm stucked since then. Also, I read somewhere that the "required" attirbute on the input fields would be enough to jQuery Validation works, but, in fact, the validation that is working (in the other input fields) is that of HTML5.

    How to make it work?

  • Google reCaptcha + custom form validation: Can I run .execute() synchronous?

    I use reCaptcha+validation jQuery plugin:

    <script>
      $('#contact_us-form').validate({
        submitHandler: function(form) {
          grecaptcha.execute(); //How to run this syncly?
          $(form).ajaxSubmit({ ... }); // This request without token
        }
      });
    </script>
    <form>
        ...
        <div class='g-recaptcha' ... />
    </form>
    

    This code almost works. Almost because execute is run async and response is come after ajaxSubmit submits form data.

    The work around is to assign callback property for g-recaptcha and move ajaxSubmit into that callback:

    var my_callback = function() {
      $(form).ajaxSubmit({ ... });
    }
    
    <div class='g-recaptcha' data-callback='my_callback'/>
    

    But this looks hairly. Furthermore the form variable is not available from my_callback thus I can not reuse this call back between similar forms.

    Is there a way to execute synchronously?