javascript - Why "$(this)" doesn't work in the following example -


this question has answer here:

html:

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

jquery

$(function () {          if (!$(".test").val()) {         alert("empty");             $(this).addclass("removeme");         } else {         alert("not empty");             $(this).addclass("addme");         }  }); 

why $(this) doesn't work here? , possible if, there's more 1 element(.test) include, example 3: if (!$(".test, .test2, .test3").val()) {

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

to achieve require best cache selector , use again add required class, this:

$(function () {   var $test = $('.test');    if (!$test.val()) {     console.log("empty");     $test.addclass("removeme");   } else {     console.log("not empty");     $test.addclass("addme");   } }); 

what possible if, there's more 1 element include, example 3: if (!$(".test, .test2, .test3").val()) {

in case you'd need test each element individually:

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

Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -