user1763879
user1763879

Reputation: 7

Increment counter onclick

I have set the number X to 5. When clicking a button a script is run to update the database without refreshing - that works fine. Now i want a number on the page to update to 6, also without the page refreshing. I tried JS, but ended up having the number in an input field which looks bad. Is there any other way, maybe with jQuery.

Upvotes: 1

Views: 1402

Answers (3)

Kamil
Kamil

Reputation: 13941

You don't have to use jQuery.

You can update everything on page by pure JavaScript, without jQuery.

Example from Javascript Tutorial at tizag.com:

<script type="text/javascript">
    function changeText()
    {
    document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
    }
</script>

<p>
    Welcome to the site <b id='boldStuff'>dude</b>
</p> 

<input type='button' onclick='changeText()' value='Change Text'/>

Upvotes: 0

charly
charly

Reputation: 956

with jquery $("your containerselector").html(parseInt($("your containerselector").html()) + 1) Though you need to be sure your container just contains on int.

Upvotes: 0

Jon Taylor
Jon Taylor

Reputation: 7905

This will let you get the element by its id and update its value.

 document.getElementById('theId').innerHTML = newValue;

If you are not currently using jQuery then do not use it just for this. If you are using jQuery you can do the following.

 $('#theId').html(newValue);

or

 $('#theId').text(newValue);

Depending on whether the newValue may or may not have html in it.

Both the jquery and straight javascript examples are equivalent.

Upvotes: 1

Related Questions