Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • $(this) vs this in jquery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 121
    Comment on it

    this refers to the current element while $(this) is the jQuery object which is constructed with that element . Using $(this) we can enable jquery functionalities while if we use this it has only generic javascript functionalities. When we need to access the basic javascript methods always use this while if you are using jquery use $(this). Sometime it is much quicker to use this instead of $(this). For example

    $(".chkbox").change(function(){ 
        if(this.checked) 
           alert("checked"); 
    });
    
    $(".myCheckboxes").change(function(){ 
          if($(this).is(":checked")) 
             alert("checked"); 
    });
    

    this reference a javascript object while $(this) is used to encapsulate with jQuery

    var name = $(this).attr('name');
    $(this).css('background-color','red')
    
    // Getting form object and its data and work on..
    this = document.getElementsByName("newvar")[0]
    formData = new FormData(this)
    
    // Calling blur method on find input field with help of both as below
    $(this).find('input[type=text]')[0].blur()
    
    //Above is equivalent to
    this = $(this).find('input[type=text]')[0]
    this.blur()
    
    //Find value of a text field with id "index-number"
    this = document.getElementById("index-number");
    this.value
    

    or

    this = $('#index-number');
    $(this).val(); 
    $(this).css('color','red')
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: