Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Multiple Checkboxes Validation

This is a regular problem and solution is hardly available on google. When we use multiple checkboxes of same group (same name with square brackets) and you've to read the values from server side, then below solution will help you. Here I'm using jQuery (https://jquery.com/) and jQuery Validate plugin (https://jqueryvalidation.org/)

For an example, I've to ask a user which of the listed book they are interested to know about


 
 <form id="BooksForm" method="post" name="BooksForm">
 <p>Books you are interested in </p>
    <input class="Books" id="Book1" name="Books[]" type="checkbox" value="1" /> The Inner Game of Tennis <br />
    <input class="Books" id="Book2" name="Books[]" type="checkbox" value="1" /> Monk who sold his ferrari <br />
    <input class="Books" id="Book3" name="Books[]" type="checkbox" value="1" /> Leading Without Authority <br />
    <input class="Books" id="Book4" name="Books[]" type="checkbox" value="1" /> Life's Amazing Secrets <br />
    <label class='error' for='Books[]'></label>
    <input id="Submit" name="Submit" type="submit" value="Submit" />
 </form>
 
 <script crossorigin="anonymous" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
 <script crossorigin="anonymous" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
 
 <script>
    $.validator.addMethod('Books', function (value, element) {
      return value > 0;
    }, 'Please select at least one checkbox');

	$('#BooksForm').validate({
      ignore: [],
      submitHandler: function(){
        alert($('.Books').val());
        return false;
      }
   });
</script>

WYSIWYG super light editor with jQuery & Bootstrap

Yes! It is. Summernote is the super light WYSIWYG editor for the web. It supports most of the features tinyMCE or CKEditor does but with smallest Javascript & CSS files.

You can download Summernote from here. It is the official website for the same. It has very simple getting started tutorial. 

This is article will show you how to start with summernote and couple of fixes or plugin which you don't find on the official website.

Getting started:
If you want to download and start with, click here.
For CDN, place below snippet under head tag.


<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> 
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script> 

<!-- include summernote css/js -->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>
  
Now create a textarea and attach summernote to it.

<textarea id="Description" name="Description"></textarea>

$(document).ready(function(){
   $('#Description).summernote();
});

When you don't want to show/use all the buttons in the toolbar, then you can choose/define like below
$('#Description').summernote({toolbar: [
       // [groupName, [list of button]]
       ['style', ['bold', 'italic', 'underline', 'clear']],
       ['font', ['strikethrough', 'superscript', 'subscript']],
       ['fontsize', ['fontsize']],
       ['para', ['ul', 'ol', 'paragraph']],
       ['insert', ['picture', 'link', 'video', 'table', 'hr']]
     ]});

That's it! But, if you are using summernote in Bootstrap modal, then there is a small problem. Whenever you click on Image, Video or link buttons another modal opens up with the options and while closing the second modal it will close all the modals. Quick fix: You can add this line of code as option to summernote.
$('#Description').summernote({
  dialogsInBody: true,
  toolbar: [ 
    // toolbar code if needed
  ]
});

Summernote inserts base64 code (image data URL) for any image inserted. If you don't want to store image data URL in the text (as it will hold huge data), then you can use below code:
$('#Description').summernote({
  dialogsInBody: true,
  toolbar: [ 
    // toolbar code if needed
  ],
  callbacks: {
      onImageUpload: function(image) {
          uploadImage(image[0]);
      }
  }
});

function uploadImage(image) {
    var data = new FormData();
    data.append("file", image);
    $.ajax({
        url: SITE_URL + "admin/upload-image",
        cache: false,
        contentType: false,
        processData: false,
        data: data,
        type: "post",
        success: function(url) {
            var image = $('').attr('src', url);
            $('#Descrpition').summernote("insertNode", image[0]);
        },
        error: function(data) {
            //console.log(data);
        }
    });
}

PHP code to upload an image to any directory and return URL for the image:

if (isset($_FILES['file']['name'])) {
    if (! $_FILES['file']['error']) {
        $name = md5(rand(100, 200));
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $filename = $name . '.' . $ext;
        $destination = $this->getMediaPath() . 'images/' . $filename;
        $location = $_FILES["file"]["tmp_name"];
        move_uploaded_file($location, $destination);
        echo 'media/images/' . $filename;
    } else {
        echo "Ooops!  Your upload triggered the following error:  " . $_FILES['file']['error'];
    }
}            

That's it...

Validation and Submission of form using jQuery :: Easiest Solution

In any application, form validation and submission to server is so common and redundant; there are multiple ways of doing it. And the best and easiest way that I do use or recommend is jQuery solution. 

Most popular jQuery plugins are the best solution, they have the best solution ever. 

One, jQuery Validator written and maintained by Jorn Zaefferer, a member of the jQuery team, lead developer on the jQuery UI team and maintainer of QUnit.

Two, jQuery Form by malsup, it has various plugins and solutions. Another plugin that I like from same developer is jQuery BlockUI. (give a try).


 
 
 
 
 
Name:
Email:
Note: To avoid unexpected behavior, maintain same form and fields names and id selector values. Need further explanation, let me know.

Email already exists using jQuery

It is the common requirement for any web application either it is PHP, .net, JSP etc., which has users involved. When creating/adding user from admin or end user registration we should check whether username or email address already exists. It will help to have unique registrations to our application and avoid confusion between various users. 

I see many developers struggle with this by submitting the form to server side script and validate their from database, in case username/email address already exists they take the pain to go back to previous page or form and show the error message with other form data filled. 

Few use AJAX to send the information onblur or onkeyup or onkeydown but face difficulties to stop form submission. Here is the simple solution that would help in validating username or email address existence without much hassle. 

Solution comes from popular jQuery Validator plugin I'm using this from ages. 

HTML Code:
<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
        <script>
              $(function(){
                    $('#UserForm').validate({
                           rules:{
                                   Name: {required: true},
                                   EmailID: { required: true, email: true, 
                                     remote: {
                                        url: "http://localhost/user/check-email",
                                        type: "post",
                                        data: {
                                              EmailID: function() {
                                                  return $( "#EmailID" ).val();
                                              },
                                              UserID: $('#UserID').val()
                                        }
                                     }
                                 }
                           }   
                    });
              });
        </script>
    </head>
    <body>
        <form action="" id="UserForm" method="post" name="UserForm">
            Name: <input id="Name" name="Name" type="text" />
            Email ID: <input id="EmailID" name="EmailID" type="text" />
            <input id="UserID" name="UserID" type="hidden" value="0" />
            <input id="Submit" name="Submit" type="submit" value="Submit" />
        </form>
</body>
</html>

 The remote block will do the trick, it sends the current field value to server side URL "http://localhost/user/check-email". This URL can be any file URL where it sends EmailID value using POST method and there you've to write SQL query to search in DB and if exists print 'false' otherwise 'true'. (Note: don't write return true or return false, just print true or false in quotes)

We can pass UserID as zero for new insertion for update UserID can be unsigned integer so that you can check if EmailID is same for other than selected UserID.