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

Wednesday 23 July 2014

jQuery validation for file type extension

jQuery validation for file type extension

<script type="text/javascript">
  $(function(){
    $('input#submit').click(function(){
      var file = $('input[type="file"]').val();
      var exts = ['doc','docx','rtf','odt'];
      // first check if file field has any value
      if ( file ) {
        // split file name at dot
        var get_ext = file.split('.');
        // reverse name to check extension
        get_ext = get_ext.reverse();
        // check file type is valid as given in 'exts' array
        if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
          alert( 'Allowed extension!' );
        } else {
          alert( 'Invalid file!' );
        }
      }
    });
  });
</script>

Tuesday 22 April 2014

jQuery: Difference between parent(), parents() and closest()

HTML

<xmp>
<html lang="en">
  <head>
     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  </head>
  <body>
     <div>
        
            <a href="https://www.blogger.com/blogger.g?blogID=5288802523561781990#" id="anchorTag">Click here</a>
         


      </div>
</body>
</html>

jQuery
   $('#anchorTag').parent();      //This would return p, immediate parent of a#anchorTag.
parents(selector) : This returns the multiple ancestors. Its not restricted to only one level of parent/ancestors of the element. This is the main difference between the parent and parents method.
In the above HTML Snippet. If i do
   $('#anchorTag').parents();        //This would return all the ancestors (p, div, body, html)

   //On passing selector it will filter down the matched parent elements by selector

   $('#anchorTag').parents('div');   //This would give me only div
closest(selector) : It works like parents(), except that it returns only one parent/ancestor. This is ideal for the situation i mentioned earlier. If i want to check for existence of element in the ancestry tree, then i would prefer to use the closest rather than parents as it only target the selector rather than filtering it from all the ancestor elements. Here is example
$('#anchorTag').closest();           //This would give me empty object as we have not mentioned the selector
$('#anchorTag').closest('div');      //This would give me the div.
Hope this post has helped in terms of using the parent, parents and closest methods of jQuery library. Thank you for reading.