I'm surprised you're getting as far as 20050
. The code shouldn't really work at all.
$('div [name = total[]]')
Firstly, that's not a valid selector. You would have to escape or quote the attribute selector, otherwise the first ]
in it closes the selector, leaving an invalid trailing second ]
.
It is only working at all because of a quirk (bug) in selector-parsing in jQuery/Sizzle. But because it's non-standard, (a) it might break in the future, and (b) it won't take advantage of the fast native querySelectorAll
in modern browsers. Better:
$('div [name="total[]"]')
However you would need jQuery 1.4 for this because jQuery 1.3's attribute selector parsing was even more buggy and broke this case.
It might be better to avoid all these issues by just assigning a class
to those elements and selecting on that instead.
$('div [name = total[]]').text()
What are the elements inside the div
that have name="total[]"
? I am supposing they are some sort of form controls otherwise the name
attribute would be invalid. But text()
is not the right way to read a form control. It gives you the textual content inside the element's tags, not the current value of the field.
<input>
s don't have textual content. <textarea>
does have textual content, but it is not necessarily the same as the field's value. The textual content, like the value
attribute of <input>
, is the default-value of the field, not the current value. You should use val()
to read the current value.
var totArray = $.makeArray(name);
That's no use. By calling text()
on the selector wrapper object you have already thrown away the multiple elements you have in there to turn them into one text string. You can't get them back from a string. All makeArray
does is give you an Array containing that single string as an item.
What you need to do is read the value of each input in turn, separately, in order to add them together.
var total= 0;
$('div [name="total[]"]').each(function() {
total+= +$(this).val();
});
$("#target1").text(total);
(The +
converts the value string into an integer, as per Andy's answer.)