Reputation: 382
How do I convert the jquery code below to prototype?
<script>
$(document).ready (function() {
$("#valor").keyup(function(){
var resultVal = 0.0;
var objRegExp = '\s+';
$("#valor").each ( function() {
resultVal += parseFloat ( $j(this).val().replace(/\s/g,'').replace(',','.'));
});
$("#total").val(resultVal);
});
});
</script>
Thanks.
Upvotes: 0
Views: 914
Reputation: 2853
Here's a working example with the migration:
eventObserver = function() {
var resultVal = 0.0;
var objRegExp = '\s+';
$$(".valor").each(function(el) {
resultVal += parseFloat($(el).getValue().replace(/\s/g, '').replace(',', '.'));
});
$("total").setValue(resultVal);
};
$$('.valor').each(function(el) {
el.observe('keyup', eventObserver);
});
From your code, I supposed you have several inputs with the same id
(valor
). If this is the case, that's wrong, as ids must be unique in the whole DOM.
That's why I changed that for a class
named valor
.
Prototype has a special $$
function to get elements by css-selector. But uses $
for id search or to turn a DOM element into a Prototype-empowered element.
When calling to each
method, instead of using this
as every element in the original collection (like you do in jQuery), you must use the first argument in the function: el
.
Instead of calling the keyup
jQuery method, you must use observe('keyup', ...
.
In my opinion, jQuery is more elegant, or at least, the Prototype that I know is not that fancy :)
Upvotes: 2
Reputation: 225281
I don't know, but pure JavaScript is always nice:
function doLoad() {
var valor = document.getElementById("valor");
valor.onkeyup = function() {
var resultVal = 0.0;
var objRegExp = '\s+';
for(var i = 0; i < valor.childNodes.length; i++) {
var n = valor.childNodes[i];
if(n.nodeType === 1) resultVal += parseFloat(n.value.replace(/\s/g, '').replace(',', '.'));
}
document.getElementById("total").value = resultVal.toString();
};
}
if(window.addEventListener)
window.addEventListener("load", doLoad, false);
else
window.attachEvent("onload", doLoad);
Upvotes: 3