Continued from here Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal
Working JSFiddle: http://jsfiddle.net/tbq8eo8b/10/ (it calculates total, in Drupal it calculates zeros - why?)
Raw:
$(document).ready(function () {
var $selects = $("select").change(function (e) {
var total = 0;
$selects.each(function() {
var val = this.value.match(/\$(\d+)/);
total += val ? +val[1] : 0;
});
$(".total").val(total);
});
});
Drupal:
(function ($) {
Drupal.behaviors.totalAmount = {
attach: function(context, settings) {
/*Add your js code here */
var $selects = $("select").change(function (e) {
var total = 0;
$selects.each(function() {
var val = this.value.match(/\$(\d+)/);
total += val ? +val[1] : 0;
});
$(".total").val(total);
});
}
};
})(jQuery);
2nd attempt with internal Drupal:
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script>
$(document).ready(function () {
var $selects = $("select").change(function (e) {
var total = 0;
$selects.each(function() {
var val = this.value.match(/^\$(\d+)$/);
total += val ? +val[1] : 0;
});
$(".total").val(total);
});
});
</script>
As you see the code is identical (except Drupal wrappings), so why it's not working on Drupal? Why it prints zeros in .total field, but in JSFiddle it works fine?
console.log(this.value);
just before or aftervar val = this.value.match(/^\$(\d+)$/);
and tell us what's there. Similarly,console.log($selects.count);
before ` $selects.each(function() {`, please :) – Mołot 14 hours agoconsole.log( val ? +val[1] : 0 );
? I have my suspicion now, but I need to know this one thing, to confirm or discard it before I'll post answerer. – Mołot 12 hours ago