Reputation: 309
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!
Upvotes: 0
Views: 64
Reputation: 61056
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.
Upvotes: 1