Keleko
Keleko

Reputation: 243

If-else JavaScript not working

Whats wrong with this script? It resets itself and the second div never changes. I'm missing something? I'm thinking I probably need a better way to handle the variable so if someone knows of one that would be awesome. This is my jsfiddle testing script:

var lang="de";

$('#en').click(function () {
    lang="en";
});
$('#de').click(function () {
    lang="de";
});
$('#es').click(function () {
    lang="es";
});

function showtext() {
    $('#text').text(lang); 
    if (lang="en") {
        $('#cur').text(lang);
    }
    else if (lang="de") {
        $('#cur').text(lang);
    }
    else if (lang="es") {
        $('#cur').text(lang);
    }
}

showtext();

setInterval(function () {
    showtext();
}, 2000);

Demo on jsfiddle

Upvotes: -1

Views: 105

Answers (3)

Jesse
Jesse

Reputation: 8759

Your function is doing assignment through =, for comparison you must use ==.

function showtext() {
    $('#text').text(lang); 
    if (lang == "en") {
        $('#cur').text(lang);
    }
    else if (lang == "de") {
        $('#cur').text(lang);
    }
    else if (lang == "es") {
        $('#cur').text(lang);
    }
}

jsFiddle Working demo

Upvotes: 4

isherwood
isherwood

Reputation: 61063

You have an if loop that does exactly nothing (and it uses the wrong comparison operator). Try this instead:

http://jsfiddle.net/Su3RC/158/

function showtext() {
    $('#text').text(lang);
    $('#cur').text(lang);
}

Upvotes: 0

Victor
Victor

Reputation: 666

Your comparisons are actually assignments try below:

$('#text').text(lang); 
    if (lang=="en"){
        $('#cur').text(lang);
    }
    else if (lang=="de"){
        $('#cur').text(lang);
    }
    else if (lang=="es"){
        $('#cur').text(lang);
    }

Upvotes: 0

Related Questions