56794

Why “$(this)” doesn't work in the following example [duplicate]

<div class="question-status question-originals-of-duplicate">

This question already has an answer here:

    <li> How does the “this” keyword work? <span class="question-originals-answer-count"> 20 answers </span> </li> </ul>

    <strong>HTML:</strong>

    <!-- try to change the value="" --> <input class="test" type="text" value="">

    <strong>jQuery</strong>

    $(function () { if (!$(".test").val()) { alert("Empty"); $(this).addClass("removeMe"); } else { alert("not Empty"); $(this).addClass("addMe"); } });

    Why $(this) doesn't work here? And what is it possible to do about it if, say there's more than one element(.test) to include, for example 3: if (!$(".test, .test2, .test3").val()) {

    Answer1:

    The problem is because the code runs directly within the document.ready handler and is therefore within the scope of the document, hence this refers to the document.

    To achieve what you require you would be best to cache a selector and use that again to add the required class, like this:

    $(function () { var $test = $('.test'); if (!$test.val()) { console.log("Empty"); $test.addClass("removeMe"); } else { console.log("not Empty"); $test.addClass("addMe"); } });

    What is it possible to do about it if, say there's more than one element to include, for example 3: if (!$(".test, .test2, .test3").val()) {

    In that case you'd need to test each element individually:

    if (!$('.test1').val() && !$('.test2').val() && ... ) {

Recommend

  • Add after
  • Angular 5 Material snackbar
  • Increasing dimensions on hover without changing the position of other elements
  • How to keep button state across different pages?
  • Get css animation property with jQuery
  • smarty nested if condition is not working properly?
  • Can't delete li from to-do list
  • JQuery Auto-Complete: How do I handle modifications?
  • jquery code not working without breakpoint
  • get iframe content as string
  • Simple linked list-C
  • Group list of tuples by item
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • jQuery .attr() and value
  • Display issues when we change from one jquery mobile page to another in firefox
  • Deselecting radio buttons while keeping the View Model in synch
  • Menu Color Fade on Hover with Jquery
  • MySQL WHERE-condition in procedure ignored
  • JSON with duplicate key names losing information when parsed
  • jQuery tmpl and DataLink beta
  • Web-crawler for facebook in python
  • Jquery - Jquery Wysiwyg return html as a string
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • How to disable jQuery.jplayer autoplay?
  • trying to dynamically update Highchart column chart but series undefined
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • CSS Applying specific rule for a specific monitor resolution with only CSS is posible?
  • How do I configure my settings file to work with unit tests?
  • Java static initializers and reflection
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • apache spark aggregate function using min value
  • unknown Exception android
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • Unable to use reactive element in my shiny app
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?