1

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??

1

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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") ){

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.