1

I am trying to make an jQuery function to make sum of some input fields with array name, but not same id.

<input name="ingredient[1]" type="text" id="autofield_1" class="ingrediente">

<input name="ingredient[2]" type="text" id="autofield_2" class="ingrediente">

<input name="ingredient[3]" type="text" id="autofield_3" class="ingrediente">

<input name="ingredient[4]" type="text" id="autofield_4" class="ingrediente">

<input name="ingredient[5]" type="text" id="autofield_5" class="ingrediente">

<input name="ingredient[6]" type="text" id="autofield_6" class="ingrediente">

Note: I use a button with jQuery function to add new field on press, is using appendTo to add more fields. sometimes I have more or less fields, the jQuery function must be dynamic, to apply on the number of input fields set.

4
  • What values would you expect the user to enter? What result would you want to get from those inputs? Commented Dec 1, 2013 at 18:24
  • Access them by class $( '.ingrediente' ) or name starts condition. Commented Dec 1, 2013 at 18:27
  • with sum you mean "numeric sum" or "concatenate strings"? Commented Dec 1, 2013 at 18:29
  • @BeNdErR numeric sum from input value Commented Dec 1, 2013 at 18:30

1 Answer 1

4
var sum = 0;
// or $( 'input[name^="ingredient"]' )
$( '.ingrediente' ).each( function( i , e ) {
    var v = parseInt( $( e ).val() );
    if ( !isNaN( v ) )
        sum += v;
} );
Sign up to request clarification or add additional context in comments.

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.