0

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.

1
  • 1
    if can show that you tried, you will get a higher response rate. Commented May 13, 2011 at 1:36

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Here's a working example with the migration:

http://jsfiddle.net/MaQA5/

Code:

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);
});

Some comments:

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 :)

1 Comment

I also personally prefer the jquery simplicity. However, I had conflict with a prototype plug-in. Thank you for your help and comments.

Your Answer

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.