1

I am trying to perform simple calculation using Jquery on input fields but cannot make it work.

<label for="a"><input type="number" id="a" value="1" size="2" maxlength="1"></label>
<label for="b"><input type="number" id="b" value="1" size="2" maxlength="1"></label>

<div class="button">
<a name="qtybutton" onClick="calculation()">update</a>
</div>

<script>
function calculation() {
    variable = new XMLHttpRequest();

    var total = 0;
    var sqty = $('#a').val();
    var itemprice = $('#b').val();
    var total = sqty * itemprice;

    $('#total').val(total);
    alert("OK");
}
</script>

I get alert "OK" so at least I know that jquery function is working, but no calculation is performed. I would be thankful for any suggestions.

3
  • Where is your <input id='total' type='text' /> element? You need an input to set the value of. Commented Dec 14, 2014 at 20:59
  • 1
    <p id="total">Total:</p> this is it Commented Dec 14, 2014 at 21:01
  • Okay, I posted my answer. :) Commented Dec 14, 2014 at 21:07

2 Answers 2

1

The .val() function usually is associated with inputs, whereas the .html() function puts text inside of an element. Try this:

function calculation() {
    variable = new XMLHttpRequest();

    var total = 0;
    var sqty = $('#a').val();
    var itemprice = $('#b').val();
    var total = sqty * itemprice;

    $('#total').html(total);
    alert("OK");
}
Sign up to request clarification or add additional context in comments.

Comments

1

It will work when you have an element named total:

<label for="a"><input type="number" id="a" value="1" size="2" maxlength="1"></label>
<label for="b"><input type="number" id="b" value="1" size="2" maxlength="1"></label>
<label for="total"><input type="number" id="total"  size="2"></label>

<div class="button">
<a name="qtybutton" onClick="calculation()">update</a>
</div>

Check it: http://jsfiddle.net/chc2v5qe/

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.