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>
Altay Mazlum
  • 442
  • 5
  • 15

2 Answers2

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

Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34
  • A second nice way is discribed here: http://stackoverflow.com/questions/1224133/is-it-possible-to-do-value-in-jquery – Marvin Fischer Jul 10 '15 at 10:31
  • Oh but this one doesn't work properly because when there is not the first value, it returns undefined1... – Altay Mazlum Jul 10 '15 at 10:40
  • 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. – Altay Mazlum Jul 10 '15 at 10:47
  • I mean not just jsfiddle but this will do I guess, thanks for your answer. Have a good day! – Altay Mazlum Jul 10 '15 at 10:52
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);
    });

});
Dhinju Divakaran
  • 893
  • 1
  • 8
  • 11