SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Apr 2005
    Posts
    154
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Beginner: plus operation

    I'm sure this is an easy task but I am also a beginner. Please help.

    <form name ="form">
    <input name="total" value="100" />
    </form>

    The following is a link that produces a decrease by 5 from the original "100" with every click

    <a href="javascript:void(0)" onclick="eval(document.form.total.value = document.form.total.value - 5)">Decrease by 5</a>

    However, if I use the "+"
    <a href="javascript:void(0)" onclick="eval(document.form.total.value = document.form.total.value + 5)">Increase by 5</a>

    it will not increase the number but instead will append 5 to 100, and I will end up with something like 100555555...

    Please, tell me what do I need to know about summing values, since extract, divide or multiply are working just fine using the above formula...

    Thanks!

  2. #2
    SitePoint Addict
    Join Date
    Feb 2004
    Location
    Staffordshire, UK & Florida, USA
    Posts
    314
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's because the result of the document.form.total.value is a string and the + operator is performing concatenation.

    I don't see why you need the eval() call - I would do it like this:

    Code:
    <a href="javascript:void(0)" onclick="document.form.total.value = Number(document.form.total.value) + 5">Increase by 5</a>

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,868
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    There's not much need for the anchor tag either since it isn't going anywhere.

    Code:
    <span onclick="document.form.total.value = Number(document.form.total.value) + 5">Increase by 5</span>
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Zealot
    Join Date
    Apr 2005
    Posts
    154
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Many thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •