0

I'm trying to update numbers on a page based on button pushing by a user. I have it working, but when the number updates, the text is no longer formatted like it came in a <code></code> block. Here's the code I'm using minus any effort to control the format:

<script>
    var countUp = function() {
        $("#num").html(parseInt($("#num").html()) + 1);
        $("#textWithNumInIt").html("The number is now"+$("#num").html() );
    }
</script>

<p id="textWithNumInIt"><code>The number is 0</code></p>

I've tried putting <code></code> tags inside the jQuery, with and without escape characters. I've tried using .val() and .text() to set the text in an effort to leave the formatting alone. I've tried using a span around the number itself, but then the value doesn't even update.

This is the first time I have changed HTML using jQuery inside a javascript function, so the trouble might have something to do with that. Any help would be awesome, and if you have advice on a totally different way to do this, please share.

2

3 Answers 3

2

When you edit the contents of the textWithNumInIt paragraph, the <code> tags inside that paragraph are naturally replaced as well. This should work:

$("#textWithNumInIt").html("<code>The number is now "+$("#num").text()+"</code>" );
Sign up to request clarification or add additional context in comments.

2 Comments

I had already tried that, and it didn't work. I just tried wrapping <b></b> tags around it instead, and the bold showed up. It is possible that the framework I'm working in prevents certain tags from being used inside the javascript?
No idea. As EP pointed out, a self-contained example works fine, so you need to provide us with an example where it doesn't work before we can try to figure out why.
0

Maybe try this -

$('#textWithNumInIt code').html("The number is now "+$("#num").text() )

Comments

0

When you parseInt it, it gets converted into plain text and the <code> wrapper is gone. Use this and you will be on your path.

var countUp = function() {
    var t = parseInt($("#num").text()) + 1);//using text() to avoid any unintentional html tag issues
    $("#num").html(t);
    $("#textWithNumInIt").html("<code>The number is now "+t+"</code>" );
}

or otherwise you can continue with your code by making a simple edit.

var countUp = function() {
    $("#num").html(parseInt($("#num").html()) + 1);
    $("#textWithNumInIt code").html("The number is now"+$("#num").html() );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.