user2065483
user2065483

Reputation: 1225

Select an Object with jQuery and add multiple functions to it, using (this)

This will probably sound silly, but I want to optimize my jQuery code in order to achieve something like this:

jQuery("#myid).{ // Here, how can I make it work?
    var value = jQuery(this).val();
    if(value == null || value == ""){
     jQuery(this).addClass("error");
    }
    // and so on
}

Basically, I want to select a DOM element and apply various codes to it. How can I do it?

Upvotes: 0

Views: 92

Answers (3)

palaѕн
palaѕн

Reputation: 73926

Use the anonymous function:

jQuery("#myid").addClass(function(){   // To addClass
     return this.value ? 'error' : '';
}).css('width', function() {           // For css
     return this.value || 400;
}).attr("id", function () {            // For attribute change
     return "newID";
});

Upvotes: 1

xdazz
xdazz

Reputation: 160883

If you have operation more than addClass, use .each

$("#myid").each(function() {
    var value = $(this).val();
    if(value == null || value == ""){
      $(this).addClass("error");
    }
    // and so on
});

Upvotes: 0

Blender
Blender

Reputation: 298392

Just assign it to a variable:

var $elem = jQuery("#myid");
var value = $elem.val();

if (value == null || value == ""){
    $elem.addClass("error");
}

You could also use .each(), as it'll iterate only over your single element, but it's somewhat confusing in my opinion:

jQuery("#myid").each(function(){
    var value = jQuery(this).val();
    if(value == null || value == ""){
     jQuery(this).addClass("error");
    }
    // and so on
})

Upvotes: 1

Related Questions