Coding Cheatsheets - Learn web development code and tutorials for Software developers which will helps you in project. Get help on JavaScript, PHP, XML, and more.

Post Page Advertisement [Top]

jQuery Used in Projects

1. Get the length of any class
    var numItems = $('.video_box').length;
    //Here we get the length of video_box class
2. Get the value of first class
    var sourcePath = $(".firstLoadThumb").first().val();
    //Here we get the first firstLoadThumb class value
3. Splits the text into array
    var sourcePath = "lion|dog|cat";
    animal = sourcePath.split('|');
    //It is explode the string into array. Here animal[0] return lion.
4. Load the page by jquery

5. Datepicker

    Open Datepicker on image click
    Html code:
    <div class="input-append date" id="dp3">
        <input type="text" id="datepicker" />
        <span class="add-on"><i class="icon-calendar" id="cal2"></i></span>
    // Here datepicker will open on image and textbox click
    On click event on image
    $("#calImg").click(function(e) {
    if you wanted to submit the form on selecting the date:
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        onSelect: function(dateText, inst) { $("#myform").submit(); }
    show the DatePicker when textbox gets focus and hide the datepicker after 2 seconds.
    $('#txtDate').focus(function() {
        setTimeout(function() {
        }, 2000)
    $( "#datepicker-3" ).datepicker({
       altField: "#datepicker-4",
       altFormat: "DD, d MM, yy"
      <p>Enter Date: <input type="text" id="datepicker-3"></p>
      <p>Alternate Date: <input type="text" id="datepicker-4"></p>
      off weekdays
      $( "#datepicker-5" ).datepicker({
       beforeShowDay : function (date)
          var dayOfWeek = date.getDay ();
          // 0 : Sunday, 1 : Monday, ...
          if (dayOfWeek == 0 || dayOfWeek == 6) return [false];
          else return [true];

DateRange validation
        onSelect: function (selected) {
            var dt = new Date(selected);
            dt.setDate(dt.getDate() + 1);
            $("#txtTo").datepicker("option", "minDate", dt);
        onSelect: function (selected) {
            var dt = new Date(selected);
            dt.setDate(dt.getDate() - 1);
            $("#txtFrom").datepicker("option", "maxDate", dt);
6.    Insert Element after img element
        $("img").after("<p>Hello Inserting element</p>");

    <img src="/images/xyz.gif" alt="jQuery" width="100" height="140"><br><br>
    <button id="btn2">Insert after</button>
7. Add table row in jQuery
    <table id="bootTable">
    $('#bootTable > tbody:last-child').append('<tr>...</tr><tr>...</tr>');

8. Add or remove Rows in table
<table class="form-table" id="nameFields">
        <tr valign="top">
            <th scope="row"><label for="name">Name</label></th>
                <input type="text" id="name" name="name[]" value="" placeholder="Name" /> &nbsp;
                <a href="javascript:void(0);" class="addName">Add</a>
        $("#nameFields").append('<tr valign="top"><th scope="row"><label for="name">Name</label></th><td><input type="text" id="name" name="name[]" value="" placeholder="Name" /> &nbsp;<a href="javascript:void(0);" class="remRow">Remove</a></td></tr>');

9. Get the parent element
<div class="testDemo">
<a href="javascript:void(0);" class="demo">Click Here</a>
var currentClass = $(this).parent().attr('class');
// It will return "testDemo" 

Now get the index number of parent class
var index = $('a.demo').parent().index(".testDemo");
or var index = $(this).parent().index(".testDemo");
// It will return the index number of "testDemo"

10. Use siblings to traverse nearest element or parallel
<div class="panel-heading panel-heading-link">
<a href="#collapse_42" data-parent="#accordion" data-toggle="collapse"> Stunt Reel </a>
<div id="collapse_42" > Test</div>

Suppose you want to change the panel-heading background color on basic of "collapse_42" id

If you want to remove the anchor tag of panel-heading element

11. Remove Function
If you want to remove anchor tag of testDemo class
<div class="testDemo">
<a href="javascript:void(0);" class="demo">Click Here</a>

12. Get the value of any field
<input type="text" id="booking_date">

13. Get text of any element
<p id="booking_date">Hello this is testing paragraph text</p>

14. Hide and show any element
<div id="booking_date">Hello this is testing paragraph text</div>

15. Change CSS by jQuery

16. Check wether checkbox/radio box is checked or not
<input type="checkbox" value="all" id="checkFrnd" name="all">

if($("#checkFrnd").prop('checked') == true){
if ($("#checkFrnd").is(":checked")) {
Check or Uncheck bootstrap checkbox
$('#allCheck').click(function() {

$('input[type="checkbox"]').prop('checked', true);
$('.checkAll').on('click',function(){ if($(this).prop('checked') == true){ $('.checkOnce').prop('checked',true); }else{ $('.checkOnce').prop('checked',false); } });
17. Get the value and text of selected option
   <select id="userName">
<option value="1">Sudhir</option>
<option value="2">Karan</option>
<option value="3">Sumit</option>
<option value="4">Amit</option>

$("#userName" ).val(); // Get the value
$( "#userName option:selected" ).text(); // Get select option text

18. Calculate the sum of same class of input field
    var sum = 0;
sum += parseFloat($(this).val());

19. Jquery toggle class 
//Add or remove class by single function.In this we highlight the div after every 3 click.

<div> Highlight the div </div>

var $thisParagraph = $('div');
var count = 0;
$ {
$thisParagraph.toggleClass( "highlight", count % 3 === 0 );

20. jQuery Slide example.
<div class="demo"> Testing for hide and show div</div>
<a href="javascript:void(0);" id="hide">Click to hide</a>
<a href="javascript:void(0);" id="show">Click to show</a>

  $(".demo").hide( "slide", { direction: "down"  }, 2000 );

  $(".demo").show( "slide", {direction: "up" }, 2000 );

  $(".demo").slideToggle( 'slow');

21.Empty form on click event
.not(':button, :submit, :reset, :hidden')
22. Use of mouseout function

23. Form submit on pressing "Enter" button
$('form').each(function() {
$(this).find('input').keypress(function(e) {
// Enter pressed?
if(e.which == 10 || e.which == 13) {
return _functionLogincheck();

24. Blocking keyCode
// Prevent F12 button
return false;
}else if(event.ctrlKey && event.shiftKey && event.keyCode==73){      
return false;  //Prevent from ctrl+shift+i

// Prevent right click
  return false;

25.Open and close bootstrap model
<a href="javascript:void(0);" class="btn btn-primary btn-lg openModel">
 Launch demo modal
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
<div class="modal-body">
<a class="custom-close"> My Custom Close Link </a>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->

$(function () {
$(".custom-close").on('click', function() {
$(".openModel").on('click', function() {

26. jQuery closest and find method
The .closest selector traverses up the DOM to find the parent that matches the conditions.
the .find selector traverses down the DOM where the event occurred, that matches the conditions.

closest selector example with html and javascript
<div class="rel-wrap">
<img src="" width="920" height="300" class="my-img">
<div class="my-div">
second div
        $(this).closest('.rel-wrap').find('.my-div').animate({left: '0px'}, 1000);
        $('.my-div', this).delay( 1000).animate({left: '-940px'}, 500);

27. Slide readmore options
<div class="about-text">
<b>Tina France</b>
<p>Being fascinated with sound from the very early age inspired her to concentrate on getting trained as a classical singer and a composer.<br/> <a href="#" class="show-about">Read More</a></p>

<div class="about-hidden">
<p>She did her training Under Soprano Patricia MaCmahon at RSAMD and composers William John Sweeney and Nick Fells at the university of Glasgow.

$(this).text($(this).text() == 'Read More' ? "Show Less" : "

28. Get the visible first element of class
<ul class="demo1">
<li class="news-item" id="1"></li>
<li class="news-item" id="2"></li>
<li class="news-item" id="3" style="display:none;"></li>
<li class="news-item" id="4" style="display:none;"></li>
var first = $('ul.demo1').find('li:visible:first').attr('id');

29. Multiple event on single selector
mouseenter: function(){
$(this).css("background-color", "lightgray");
mouseleave: function(){
$(this).css("background-color", "lightblue");
click: function(){
$(this).css("background-color", "yellow");

30. How to Scroll to the top of the page?
var xCoord=200;
var yCoord=500;
window.scrollTo(xCoord, yCoord);

31. Fadein and fadeOut elements in stack format 
i.e first come Last out
function fadeIn(){
$("li").each(function(i) {
function fadeOut(){
$($("li").get().reverse()).each(function(i) {

FadeOut element after some interval

32. Remove duplicate row of table
function removeDuplicateRow(){
var seen = {};
$('#searchcus>table>tbody> tr').each(function() {
var txt = $(this).text();
if (seen[txt])
seen[txt] = true;

or you can use:
var addedProductCodes = [];
$('input:button').click(function () {
var td_productCode = $("#sales-product-code").val();
var index = $.inArray(td_productCode, addedProductCodes);
if (index >= 0) {
alert("You already added this Product");
} else {
$('#test tr:last').after("<tr><td>data[" + td_productCode + "]</td></tr>");

33. Dynamically moving rows up and down jquery
<td>Element 1</td>
<span class="up"> Move up</span>
<span class="down"> Move Down</span>

<td>Element 2</td>
<span class="up"> Move up</span>
<span class="down"> Move Down</span>
<td>Element 3</td>
<span class="up"> Move up</span>
<span class="down"> Move Down</span>

$('.up,.down').click(function () {
var row = $(this).closest('tr');
if ($(this).is('.up')) {
}else {

34. Create radio buttons behave like single-choice checkboxes Html: <p><label><input type="radio" name="question1" value="morning"> Morning</label><br> <label><input type="radio" name="question1" value="noon"> Noon</label><br> <label><input type="radio" name="question1" value="evening"> Evening</label></p> <script> $(document).ready(function(){ $("input:radio:checked").data("chk",true); $("input:radio").click(function(){ $("input[name='"+$(this).attr("name")+"']:radio").not(this).removeData("chk"); $(this).data("chk",!$(this).data("chk")); $(this).prop("checked",$(this).data("chk")); }); }); </script>

No comments:

Post a Comment

Bottom Ad [Post Page]