SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Nov 2012
    0 Post(s)
    0 Thread(s)

    refresh input field on button click

    I have this form where the user can insert a quantity in an input field, and see the total in another input field. It works when you insert the numbers manually and I want it to work with buttons too, but i just can't get it to work.

    Here's the code:

    Code HTML4Strict:
    <form id="buyForm" method="post" action="cart.php">
        <label>Choose quantity</label>
            <a href="#" class="button">(+)increase</a>        
            <input type="text" id="qty1" name="qty[]"/>
            <a href="#" class="button">(-)decrease</a>
        <input type="text" id="cost1"  value="50" style="display:none; visibility:hidden;" name="cost[]" />
        <input type="text" id="price1" name="price[]" />

    Code JavaScript:
    // Calculate
    function calc(idx) {
      var price = parseFloat(document.getElementById("cost"+idx).value)*
      //  alert(idx+":"+price);  
      document.getElementById("price"+idx).value= isNaN(price)?"0.00":price.toFixed(2);
    window.onload=function() {
      document.getElementsByName("qty[]")[0].onkeyup=function() {calc(1)};
      document.getElementsByName("cost[]")[0].onkeyup=function() {calc(1)};
    //Increase/decrease buttons
    $(function() {
        $(".button").click(function() {
            var $button = $(this);
            var oldValue = $button.parent().find("input").val();
            if ($button.text() == "+") {
              var newVal = parseFloat(oldValue) + 1;
              // AJAX save would go here
            } else {
              // Don't allow decrementing below zero
              if (oldValue >= 1) {
                  var newVal = parseFloat(oldValue) - 1;
                  // AJAX save would go here

    Here it is as jsfiddle:

    Can someone please help me with this?

    Thanks in advance!

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Christchurch, New Zealand
    101 Post(s)
    4 Thread(s)
    Get rid of the text type and use a number type instead. That way the user can use the spin buttons. That's the easiest way.

    HTML Code:
        <input name="qty[]" id="qty1" type="number" />
    You can restrict the numbers to be within a certain range too.

    HTML Code:
        <input name="qty[]" id="qty1" type="number" min="1" max="10" />
    For details please see

    If you want to support older web browsers that don't know how to do number input fields, a polyfill can be found at
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Posting Permissions

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