0

I got a bunch of input fields like this:

<input type="text" class="amount" data-type="amount[aquisition][000014]" value="16.20">
<input type="text" class="amount" data-type="amount[aquisition][000014]" value="11.60">
<input type="text" class="amount" data-type="amount[aquisition][000345]" value="9.10">
<input type="text" class="amount" data-type="amount[aquisition][000345]" value="5.40">

I want to add up the values of the elements wich have [aquisition] and the following number that is unknown but where there are several of in the same document.

Tried to work with each(); but it wont work when theres more then one bracket. I am also able to modify the way the HTML input fields are generated.

$('[data-type="amount[aquisition]"]').each(function(){
 console.log($(this));
 });

I would expect the above to loop over all elements with amount[aquisition] and return arrays for each unique second set of brackets. But nothing happens, not even an error.

Any ideas?

Thx!

asked Apr 7, 2014 at 13:23
2
  • Tried to work with each();: why don't you share that code? Commented Apr 7, 2014 at 13:26
  • Yep can you post what you've already tried, it can be a matter of chars escaping :/ Commented Apr 7, 2014 at 13:28

1 Answer 1

1

You should use a partial attribute selector:

// match data-type values beginning with "amount[aquisition]"
$('[data-type^="amount[aquisition]"]').each(function(){ ... });
// match data-type values containing "amount[aquisition]"
$('[data-type*="amount[aquisition]"]').each(function(){ ... });

http://jsfiddle.net/isherwood/76tvB/1

You'd then use some string parsing to grab the value from the second set of brackets.

http://jsfiddle.net/isherwood/76tvB/4

var myNums = [];
// match data-type values beginning with "amount[aquisition]"
$('[data-type^="amount[aquisition]"]').each(function () {
 $(this).css('color', 'red');
 var myNum = $(this).attr('data-type');
 myNum = myNum.replace('amount[aquisition][', '').replace(']', '');
 myNums.push(myNum);
 $('#dropbox').text( myNums );
});

You'll have to do a check against the array to filter duplicates.

answered Apr 7, 2014 at 13:42
Sign up to request clarification or add additional context in comments.

2 Comments

Updated second fiddle to use an actual array.
This did the trick, thank you very much! I did not know about partial attribute selectors yet.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.