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:

HTML

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

Js

// Calculate
function calc(idx) {
  var price = parseFloat(document.getElementById("cost"+idx).value)*
              parseFloat(document.getElementById("qty"+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
          }
        }
        $button.parent().find("input").val(newVal);
    });

});

Here it is as jsfiddle: http://jsfiddle.net/rcheH/5/

Can someone please help me with this?

Thanks in advance!

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.


<div>
    <input name="qty[]" id="qty1" type="number" />
</div>

You can restrict the numbers to be within a certain range too.


<div>
    <input name="qty[]" id="qty1" type="number" min="1" max="10" />
</div>

For details please see http://diveintohtml5.info/forms.html#type-number

If you want to support older web browsers that don’t know how to do number input fields, a polyfill can be found at http://github.com/jonstipe/number-polyfill