Cookies com valores inteiros

Colocar valores inteiros dentro do cookie para poder fazer operações matemáticas.

Converte pra inteiro com a função parseInt quando for ler do cookie.

https://www.w3schools.com/jsref/jsref_parseint.asp

1 curtida

Mas como faço para colocar o valor de um cookie numa variavel?

var numero = parseInt(getCookie("cookie_name"));
1 curtida

Algo assim?

function pontos() {
document.cookie = “pontos=100”
var numero = parseInt(getCookie(“pontos”));
alert(``${numero}`)
}

Assim:

1 curtida

Não funcionou dessa maneira. O não tem valor dentro do cookie, está mostrando “NaN” no alert.

O exemplo ai funciona nesse site. Seu código nao sei como ta.

1 curtida
<script>

    function altCertas() {
        document.getElementById('alt1').style.backgroundColor = "#00ff00"
        document.getElementById('titulo').style.backgroundColor = "#00ff00"
        trocarPag()
        pontos()
    }

    function altErrada(ctx) {
        ctx.style.backgroundColor = "#ff0000";
       document.getElementById('titulo').style.backgroundColor = "#ff0000"
        trocarPag()
    }

    function trocarPag() {
        setTimeout(function mudar() {
            window.location.href = "pergunta_2.html"
        }, 3000)

    }

    function getCookie(name) {
        var pattern = RegExp(name + "=.[^;]*")
        var matched = document.cookie.match(pattern)

        if (matched) {
            var cookie = matched[0].split('=')
            return cookie[1]
        }
        return "";
    }

    function pontos() {
        document.cookie = "pontos=100"
        var numero = parseInt(getCookie("pontos"))
        alert(numero)
    }
</script>

Copiei/colei seu código e funcionou a chamada da funcao pontos():

1 curtida

Lembre-se que pra funcionar na sua maquina voce precisa ter pelo menos um servidor http local.

1 curtida

Ah, então é esse o problema. Porque o resultado que aparece no alert é NaN.
Sou iniciante na área e não sei muito bem desses negócios de server aí.

Eu uso IIS Express. Mas tem vários outros, como Apache, nginx, etc. É só pesquisar por http web server.

1 curtida

Ok! Muito obrigadoo!!

Desse jeito colocando em todas as paginas de perguntas o cookie sempre reseta, certo? Então o jeito seria colocar em um arquivo separado JS para ser chamado. Mas não consigo colocar em outro arquivo, sempre reseta novamente.

<script>

    function altCertas() {
        document.getElementById('alt1').style.backgroundColor = "#00ff00"
        document.getElementById('titulo').style.backgroundColor = "#00ff00"
        trocarPag()
        pontos()
    }

    function altErrada(ctx) {
        ctx.style.backgroundColor = "#ff0000";
        document.getElementById('titulo').style.backgroundColor = "#ff0000"
        trocarPag()
    }

    function trocarPag() {
        setTimeout(function mudar() {
            window.location.href = "pergunta_2.html"
        }, 3000)
    }

    function getCookie(name) {
        var pattern = RegExp(name + "=.[^;]*")
        var matched = document.cookie.match(pattern)
        if (matched) {
            var cookie = matched[0].split('=')
           return cookie[1]
        }
        return "";
    }

    function pontos() {
        document.cookie = "pontos=100"
        var numero = parseInt(getCookie("pontos"))
        alert(numero)
    }

</script>

Abre um outro tópico, pq a questão já outra.