0

I have the following code

$(document).ready(function () {
    $('#big_1').change(function () {
        var bigAmt = document.getElementById("big_1").value
            + document.getElementById("big_2").value
            + document.getElementById("big_3").value
            + document.getElementById("big_4").value
            + document.getElementById("big_5").value
            + document.getElementById("big_6").value
            + document.getElementById("big_7").value 
            + document.getElementById("big_8").value
            + document.getElementById("big_9").value
            + document.getElementById("big_10").value;

        var elem = document.getElementById("totalBig");
        elem.value = bigAmt;
    });
});

I actually wanted to add the value of big_1 to big_10 on input text value change of "big_1 to big_10" either 1 of the textfield change its value, this should be invoke.

as of now i only run on big_1 change event.

I get an javascript error by adding this way, I think the way I add them up is quite messy.

What should I do to change my code so I can sum up

big_1 to big_10 textfield value, and on change of big_1 to big_10(any of them), it will invoke this and change span id="totalBig" to the value of their sum (big_1 add until big_10)

Below is my edited extra code:

<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_1" id="big_1" size="6">

<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_2" id="big_2" size="6">


all the way until big_10

I wanna on change value of any of this big_Identifier(1-10), it will sum it up and change my

<div class="well">
Total Big: <span id="totalbig">0</span> &nbsp;&nbsp;&nbsp;&nbsp;</span> 
</div>

I tried the

<script type="text/javascript">
$(document).ready(function() {
$('#html5Form').bootstrapValidator();
    $('.big').change(function() { 
        var bigAmt = "";

        $('.big').each(function () {
            bigAmt += $(this).val();    
        })

        var elem = document.getElementById("totalBig");
alert(bigAmt);
        elem.value = bigAmt;
    });
});
</script>

It doesn't run any alert when any of the big_ value was changed.

user3412075
  • 129
  • 1
  • 9

5 Answers5

4

It would be much better if you added a big class to every single <input id="big_NUMBER">. Then you could do this:

$(document).ready(function() {
    $('.big').change(function() { 
        var bigAmt = 0;

        $('.big').each(function () {
            bigAmt += Number($(this).val());    
        })

        $("#totalBig").val(bigAmt);
    });
});

That's much cleaner and easier to understand than what you had.

In order for this to work, you'll need to add a class to all your inputs:

<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control big" name="big_2" id="big_2" size="6"><!-- Notice the big class-->

This is the best way to group all your inputs. They are all related, so they should share a classes. You should not be calling multiple ids for functionality that's so similar.

Jorge Silva
  • 4,574
  • 1
  • 23
  • 42
  • I think OP is wanting to add numbers. – epascarello Aug 27 '14 at 19:02
  • 1
    You might convert the value of `val()` to an int or floating-point type so that you don't accidentally concatenate strings. – crush Aug 27 '14 at 19:02
  • He wants to add integers, not concatenate strings. – Ryan Aug 27 '14 at 19:02
  • I tried your solution and strangely it doesn't invoke when I change, because I tried to include a alert before var elem, it doesn't seems to work, and yes I wanted to add integer – user3412075 Aug 27 '14 at 19:03
  • have you edited your HTML? You have to add the css class to the input elements? – Jorge Silva Aug 27 '14 at 19:04
  • @JorgeSilva He might need to be shown how to update his `input` elements to contain that class. – crush Aug 27 '14 at 19:10
  • In order for my code to work you need to add a `big` class to all `inputs` ``. This is more work, but it's the right way to structure your HTML. – Jorge Silva Aug 27 '14 at 19:11
1

If you are using jquery, use it properly, it'll make your life a lot easier.

This will work for you in your case exactly

$(document).ready(function() {
    $('[id^="big"').change(function(){
        var total = (+$('#totalBig').val());
        var currentVal = (+$(this).val());
        total += currentVal;
        $('#totalBig').val(total)
    })
});

DEMO

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

You monitor the change event on all the input type text as follows:

$('input:text').change(
function () {
    alert('text changed of any text box.');
    //You can doo your code here.
});

Or...

If you want add the monitor to any selected text boxes then you will have to add any css class to those selected text boxes and then monitor those text boxes through class as follows:

$('.yourclass').change(
function () {
    alert('text changed of any text box.');
    //You can doo your code here.
});

this change event will fire when you lose focus from the text box after changing the text....

but if you want with loosing the focus (means if you want to update the count while typing) then you should use keyup event as stated in this answer.

Community
  • 1
  • 1
Hassan Baig
  • 346
  • 1
  • 10
  • All my input text that I wanna monitor is of the identifier pattern big_1 to big_10 , I wanna add their integer value together and change span id="totalBig" content into the total value of sum of all the big_1 to big_10 – user3412075 Aug 27 '14 at 19:04
  • No matter what is your identifier pattern you can use generic jquery selector like "$('input:text')" or "$('.yourclass')" as stated in my above answer. In this there will be a single event handler which wil be attached to all or selected text boxes – Hassan Baig Aug 27 '14 at 19:14
0
$(document).ready(function() {
    $('#big_1').change(function() {
        var divArray = ["big_1","big_2","big_3","big_4","big_5","big_6","big_7","big_8","big_9","big_9","big_10"];
        var bigAmt = 0;

        for(var i = 0, n = divArray.length;i<n;i++)
        {
            bigAmt += parseInt($("#" + divArray[i]).val(),10);
        }   
        $("#totalBig").val(bigAmt);
    });
});

Try the above, it should do what you're looking for. You'll probably want to use parseInt as well incase the input isn't of "number" type.

*edit, forgot the # for the id.

*edit, removed comment about considering using jquery functions because people are really sensitive.

  • 1
    Why should he use the jQuery functions simply because he is using parts of jQuery for other reasons? I'd stress that you ***not*** use jQuery for the sake of jQuery. – crush Aug 27 '14 at 19:08
  • @crush why? It's much cleaner and concise to write `$("#totalBig").val(bigAmt);` – David Sherret Aug 27 '14 at 19:10
  • 1
    @DavidSherret Really? Is it ***much*** cleaner and concise? That seems fairly subjective. Have you ever looked at the jQuery code for `val()`? It's substantially slower than accessing the JavaScript property directly. – crush Aug 27 '14 at 19:11
  • 1
    I agree with @crush. Avoid using jQuery when possible, especially for simple things like the `value` property of the DOM element. – Ryan Aug 27 '14 at 19:13
  • @crush you know, you could have just explained that valid reasoning at first instead getting super aggressive about it. Stack Overflow is used for knowledge transfer, yet instead of doing so, you've decide to troll the answer. – Christopher Aug 27 '14 at 19:14
  • @Christopher Actually, I was quite literally inquiring if you had a good reason to recommend he use jQuery to access the value rather than directly. Super aggressive? Stop reading emotion into my comments. There is none. – crush Aug 27 '14 at 19:16
  • @crush yes, doing `$("#totalBig").val(bigAmt);` is visibly more concise than doing `var elem = document.getElementById('totalBig'); elem.value = bigAmt;`—I'm talking about code clarity. Setting and getting the value of a few input elements using jQuery is no reason to be up in arms. – David Sherret Aug 27 '14 at 19:20
  • @DavidSherret You're right. `val(bigAmt)` is much more concise than `value = bigAmt;`. – crush Aug 27 '14 at 19:35
  • @crush if you didn't notice, in the code they also had to select the element. There's no reason to be childish either. – David Sherret Aug 27 '14 at 19:43
  • 1
    @DavidSherret Who's being childish here? You are trying to establish your point with a completely invalid comparison. You assigned the result of `getElementById()` to a variable first before accessing its value property all in an attempt to make it seem even less concise. The selecting of the element is inconsequential to this discussion. A responsible coder would cache the element in a variable for later reuse throughout the application, and thus, the means by which it is selected are irrelevant. Furthermore, I reject your opinion that jQuery's selector syntax is more succinct than the DOM. – crush Aug 27 '14 at 19:49
  • @crush that's true, I had just copied+pasted from the original code in the question and it's true that the reference should be cached; however, I think these points are completely irrelevant to the question at hand. In this case there will be absolutely no *noticeable* performance gains to the end user and bothering to suggest that he not use jQuery to set & get a few inputs seems a bit more like trying to start a jQuery vs vanilla JS flame war than anything else. – David Sherret Aug 27 '14 at 20:02
  • @DavidSherret You're right, in this isolated circumstance, there will be no noticeable gains. How do you know that the author doesn't intend to use this code as part of a more intensive application? How do you know how often this method will be called? Did you know that the accessing the DOM property directly is 100% faster than using jQuery's `val()`? My point is that you shouldn't just use jQuery for the sake of jQuery. If jQuery adds benefit, then use it. It doesn't really add benefit here, unless you consider that the element might not actually exist. Then val() eliminates a null check. – crush Aug 27 '14 at 20:53
  • @crush I doubt they will be, but really I don't disagree with much of what you're saying (and I don't ever use jQuery—except at work where it's in our coding standard... a few things I don't agree with). This is really not worth arguing about anymore because we're basically arguing about the point of arguing about no noticeable performance gain in this situation... so I'm going to head out. With all sincerity, have a nice evening! – David Sherret Aug 27 '14 at 21:35
0

Add class="bigs" to all inputs and then try this:

$(document).ready(function () {
    var intTotalBig;
    $('.bigs').change(function () {
        intTotalBig = 0;
        $('.bigs').each(function(){
            $thisVal = $(this).val();
            if ($.isNumeric($thisVal)){
                intTotalBig += parseInt($thisVal, 10);
            }
        });
        $("#totalBig").val(intTotalBig);
    });
});

This code check all inputs on every change and sum all of them that has a number value and ignore empty or no number values.

Check JSFiddle Demo

Moshtaf
  • 4,833
  • 2
  • 24
  • 34
  • Can I don't set class="bigs" because I got other class running on my input text, i can set id="big_" – user3412075 Aug 27 '14 at 19:10
  • @user3412075: there are no problem, add this class too, like this: `` just add this class to other classes too. – Moshtaf Aug 27 '14 at 19:16