1

Is there a better way for checking an attribute for:

  1. it exist. so value must be false if attribute doesn't exist
  2. Value is correct (boolean)
var isOwner = false;
    if ($(selectedItem).is('[data-isOwner="True"]') || $(selectedItem).is('[data-isOwner="true"]')) {
        isOwner = true;
    } else {
        isOwner = false;
    }

Now I need to check for 'True' and 'true'...

Thanks

1 Answer 1

3

You can convert the value stored in data-isOwner to lower case and only compare the value to 'true'.

if (($(selectedItem).attr ('data-isOwner') || '').toLowerCase () == 'true')

The above use of <wanted-value> || '' will make it so that if the selectedItem doesn't have the attribute data-isOwner the expression will result in an empty string, on which you can call toLowerCase without errors.

Without this little hack you'd have to manually check so that the attribute is indeed present, otherwise you'd run into a runtime-error when trying to call toLowerCase on an undefined object.


If you find the previously mentioned solution confusing you could use something as

var attr_value = $(selectedItem).attr ('data-isOwner');

if (typeof(attr_value) == 'string' && attr_value.toLowerCase () == 'true') {
  ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

I like your approache. Can it also be checked typesafe? I set the property with ASP .NET MVC4 and C# so it is a boolean. Should I parse the lowercase to a boolean? and then compare with: === true?
I think every values always comes out at string unless you parse it into something in your JS.
@LockTar if you store a value inside an element's attribute it will be of type string when using $(selector).attr (key) or the equivalent, if you want it to be handled differently you'll need to provide your own wrapper around the getter.
Thanks. it worked. I only used === because it should be saver then == 'true'

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.