kokomo
kokomo

Reputation: 77

JQuery problems with setting variables in if/else

I'm trying to set a variable to 0 if an item attribute is equal a specific string, else set the variable to 1, but I can't get it to work.

My code is like this in my javascript function:

    var variable;
    if ($(this).attr("attribute", "string"))
        variable=0;
    else
        variable=1;

For some reason, the variable always get set to 0, even if the item attribute isn't equal the specific string.

What am I doing wrong??

Upvotes: 1

Views: 2533

Answers (4)

Tom
Tom

Reputation: 269

Try $(this[attribute="string"]).

Upvotes: 0

epascarello
epascarello

Reputation: 207521

You are setting the string in your if

if( $(this).attr("attribute", "string") ){

You need to read it and compatre

if( $(this).attr("attribute") === "string") ){

Upvotes: 1

ipr101
ipr101

Reputation: 24236

Try -

var variable;
if ($(this).attr("attribute") == "string")
    variable=0;
else
    variable=1;

This compares the value of attribute "attribute" to the value "string". What you're doing at the moment is setting the value of attribute "attribute" to the value "string". I suspect this function will return a "truthy" value hence variable always being set to 0.

Upvotes: 1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

You have to use this instead:

var variable;
if ($(this).attr("attribute") == "string")
    variable=0;
else
    variable=1;

$(this).attr("attribute", "string") sets the attribute attribute to string, it doesn't test if attribute equals string.

See the attr(attributeName,value) method documentation.

Upvotes: 3

Related Questions