zelocalhost
zelocalhost

Reputation: 1183

Conditions in javascript

I have a weird problem: my conditions are not working in javascript :/

this is my code:

var myposition = $("#audioWelcome").data("myposition");

/* condition */
if (myposition == "true") {
....
}

it's incorrect ? see my example : http://jsfiddle.net/qqK5J/2/ conditions are not working and html(); or data(); doesn't work too.

what is incorrect ?

Upvotes: 4

Views: 116

Answers (4)

Felix Kling
Felix Kling

Reputation: 817238

To answer your question:

if (myposition == "true") {

doesn't work as expected because myposition is the boolean value true, which is not equal to the string value "true".

You might wonder why myposition is a boolean value. That's because jQuery converts it to a boolean:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).

So all you really have to do is change your code to set booleans instead of strings and adjust the condition accordingly:

if (myposition) {
    $(this).html("afficher le lecteur");
    $('#audioWelcome').data('myposition', false);
} else {
    $(this).html("cacher le lecteur");
    $('#audioWelcome').data('myposition', true);

}

or shorter:

$(this).html(myposition ? "afficher le lecteur" : "cacher le lecteur");
$('#audioWelcome').data('myposition', !myposition);

DEMO

Upvotes: 4

Kyo
Kyo

Reputation: 964

Removed the double quotes:

if (myposition == true) {

Updated JSFilddle at:

http://jsfiddle.net/qqK5J/5/

Updated:

    if (myposition == true) {

        $(this).html("afficher le lecteur");
        $('#audioWelcome').data('myposition', false);


    } else {

        $(this).html("cacher le lecteur");
        $('#audioWelcome').data('myposition', true);

    };

Updated fiddle at:

http://jsfiddle.net/qqK5J/10/

Upvotes: 1

extramaster
extramaster

Reputation: 2653

Great question!

It seems like javascript is confusing the "true" and "false" values when set as an attribute,

@Kyo suggested to remove the double quotes, which works, to an extent. After 3 clicks the code stops functioning as expected.

@user3391179's solution doesn't seem to work at all...

Using the toString method on $("#audioWelcome").data("myposition") will make the "true"/"false" (string) value will work as you would expect them to.

Code:

    var myposition = $("#audioWelcome").data("myposition").toString();
    /* changements via onclick */
    if (myposition == "true") {
        $(this).html("afficher le lecteur");
        $('#audioWelcome').data('myposition', false);
    } else if (myposition == "false") {
        $(this).html("cacher le lecteur");
        $('#audioWelcome').data('myposition', true);
    };

Demo: http://jsfiddle.net/qqK5J/8/

Upvotes: 1

shredmill
shredmill

Reputation: 283

Better yet ditch the == true. People won't then think you're a VB5 developer

if (myposition){}

Upvotes: 0

Related Questions