user5684207
user5684207

Reputation:

I need some troubleshooting with my HTML/JavaScript code

I am trying to create code that when you press a button, it will change the value of a variable and replace some text.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <p id="unitts">You have 0 unitts</p>
    <script type="text/javascript">
        var unitt = 0;
        function unittIncrease() {
            var unittPrev = unitt;
            unitt++;
            document.getElementById(unitts).innerHTML.replace("You have " +  unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
        }
    </script>
    <button id="unittIncrease" onclick="unittIncrease();">Digitize Unitt</button>
</body>

</html>

When I press the button, nothing happens to the text. I don't know why this does not work. Please help me!

EDIT: I am only 11 years old, please don't throw your wizard code at me.

maybe you should remove your button system and add a while loop that automatically add a unit but waits one second with a setInterval function

Upvotes: -1

Views: 59

Answers (3)

Ram
Ram

Reputation: 144679

Apart from the issues that the other answer mentions, by calling .replace method on the .innerHTML property of the element, the content of it doesn't change. You should reset the property by using the returned value of the method call:

el.innerHTML = el.innerHTML.replace(...);

Also, as you are trying to increase a number, instead of replacing all the characters, you can just replace the numeric part:

var unitts = document.getElementById('unitts');

function unittIncrease() {
    unitts.textContent = unitts.textContent.replace(/\d+/, function(n) { 
        return +n + 1;
    });
}

https://jsfiddle.net/h6odbosg/

Upvotes: -1

Jia Jian Goi
Jia Jian Goi

Reputation: 1423

Your JavaScript should be (note the unitts wrapped in quotes and the full stop removed):

 document.getElementById('unitts').innerHTML = "You have " + unitt + " unitts";

Instead of:

document.getElementById(unitts).innerHTML.replace("You have " +  unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");

In the latter, it is looking for the non-existent variable unitts instead of the string 'unitts'. Also, you are looking for the text You have x unitts. which cannot be found because in your HTML, it is just You have x unitts without the full stop.


Edit

See this plnkr.

Upvotes: 0

paopao
paopao

Reputation: 54

I think you should write the js code like this

document.getElementById('unitts').innerHTML = "You have"....

Instead of:

document.getElementById(unitts).innerHTML.replace("...")

Upvotes: 0

Related Questions