Jack_812
Jack_812

Reputation: 5

Save value from variable

I have a problem, I cannot save a value into page.

My js:

var count = 0;

switch (index) {
case 0:
    count = count - 5;
    document.getElementById("point").getElementsByTagName('p')[0].innerText = (count);
    break;
case 1:
    count = count + 2;
    document.getElementById("point").getElementsByTagName('p')[0].innerText = (count);
    break;
case 2:
    count = count + 5;
    document.getElementById("point").getElementsByTagName('p')[0].innerText = (count);
    break;
}

My html:

<div id="point">
    <p></p>
</div>

How can i save the value?

Upvotes: 4

Views: 128

Answers (2)

Martijn
Martijn

Reputation: 16113

You use innerText, which is not possible here. You can use innerHTML to make it work again.
A small jsFiddle demo to show you one works, the other wont.


Also, you can simplefy your code a lot, and making it more flexible in the same effort:

var count = 0;
switch (index) {
    case 0:
        count -= 5;
    break;
    case 1:
        count += 2;
    break;
    case 2:
        count += 5;
    break;
}
// Only once, after the switch. If you want another target for the value,
// all you have to do is change this line, instead of every case.
document.getElementById("point").getElementsByTagName('p')[0].innerHTML = count;

You do not need jQuery for this. Native JS often is faster.
If you do want to use jQuery, split the selector for optimal performance:

$('#point').find('p')

Upvotes: 0

Michael
Michael

Reputation: 4000

It's running, see my jsFiddle

var index = 0; // for demonstration, change that value

var count = 0;

switch (index) {
case 0:
    count = count - 5;
    $('#point p').text(count);
    break;
case 1:
    count = count + 2;
    $('#point p').text(count);
    break;
case 2:
    count = count + 5;
    $('#point p').text(count);
    break;
}

Note, the line $('#point p').text(count); is always the same in all cases, so you might want to put this after the switch-case.

Furthermore, I replaced your line: document.getElementById("point").getElementsByTagName('p')[0].innerText = count; by $('#point p').text(count), to make use of jQuery. Hope it helps you getting started.

Upvotes: 1

Related Questions