0

I'm trying to create a calculator, getting the values from buttons 1 to 9. Now I'd like to add a value to the textbox instead of setting it, like I want the user to be able to add 1 then 5 to make it a total of 15. How can I achieve this?

.prop sets a value, or .val so that one is out of the list.

<script>
jQuery(document).ready(function () {
    jQuery("#one").click(function () {
        jQuery("#entered").prop("value", "1");
    });

});
</script>

CSS part:

<div>
    <button id="one">1</button>
    <button id="two">2</button>
    <button id="three">3</button>
    <button id="four">4</button>
    <button id="five">5</button>
    <button id="six">6</button>
    <button id="seven">7</button>
    <button id="eight">8</button>
    <button id="nine">9</button>
    <input type="text" id="entered" disabled="disabled"  />
</div>

2 Answers 2

3

Change

jQuery("#entered").prop("value", "1");

to

jQuery("#entered").val(jQuery("#entered").val() + "1");

This will concenate the old stuff with a new entered 1

This is the full code:

<div>
    <button id="one">1</button>
    <button id="two">2</button>
    <button id="three">3</button>
    <button id="four">4</button>
    <button id="five">5</button>
    <button id="six">6</button>
    <button id="seven">7</button>
    <button id="eight">8</button>
    <button id="nine">9</button>
    <input type="text" id="entered" disabled="disabled" value="" />
</div>

jQuery(document).ready(function () {
    jQuery("#one").click(function () {
        jQuery("#entered").val(jQuery("#entered").val() + "1");
    });

});

If you want to have a function for that:

 $.fn.appendVal = function (newPart) {
   return this.each(function(){ $(this).val( $(this).val() + newPart); });
 };

 $("#abc").appendVal("test");

https://jsfiddle.net/ffp19wze/ here is a working jsFiddle for it

Sign up to request clarification or add additional context in comments.

4 Comments

A second nice way is discribed here: stackoverflow.com/questions/1224133/…
Oh but this one doesn't work properly because when there is not the first value, it returns undefined1...
Okay thanks, although I've already solved the problem with the link that you've sent to me. Thanks anyways! And If you could edit the answer with codes, I'd like to select you as the best answer.
I mean not just jsfiddle but this will do I guess, thanks for your answer. Have a good day!
2

Change your jQuery to

jQuery(document).ready(function () {
    jQuery("#one").click(function () {
        var cur_val = jQuery("#entered").val();
        cur_val = cur_val+"1";
        jQuery("#entered").val(cur_val);
    });

});

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.