Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set an attribute using jQuery

Tags:

jquery

Is there a way to conditionally set an attribute using jQuery? For example, I want to simplify this:

$(element).val('99');

if ([condition]) {
    $(element).attr('myAttr', 1);
}

This works, but forces me break the chaining of method calls. Instead, I would prefer something like this:

$(element).val('99').attr('myAttr', 1, [condition]);

So that the attribute is only set if the condition is true. How would I do this?

like image 833
matk Avatar asked Dec 02 '22 18:12

matk


1 Answers

Well you could use:

$(element).val('99').attr('myAttr',[condition] ? 1 : $(element).attr('myAttr'));

Demo here

Option 2, just: $(element).val('99').attr('attr',[condition] ? 1 : undefined).

Demo here

Please notice that this option 2, as @FrédéricHamidi mentioned, might break the chain in older versions of jQuery. But works from jQuery 1.7.2

like image 128
Sergio Avatar answered Dec 24 '22 07:12

Sergio