-1
I’m starting my Javascript study and came across a question that is to take the (monetary) value in an html class, treat and display the result without R$ in another html element. But it didn’t work.
Code:
function myFunction() {
var test = document.getElementsByClassName("entrada");
// var test = 'R$ 299,00';
function getMoney( str )
{
return parseInt( str.replace(/[\D]+/g,'') );
}
function formatReal( int )
{
var tmp = int+'';
tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
if( tmp.length > 6 )
tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");
return tmp;
}
var int = getMoney( test );
document.getElementById("saida").innerHTML = (formatReal( int ));
}
<p>Valor do item: <strong class="entrada">R$ 229,00</strong></p>
<button onclick="myFunction()">Clique para tratar</button>
<p>Valor tratado: <span style="color:red" id="saida"></span></p>
In
getMoney(test)
,test
is aNodeList
(returned bygetElementsByClassName
). Therefore, howreplace
is a string method, you cannot get it from an instance ofNodeList
. You need to get the value of the element, that is, a string. Maybe this answer can give you an additional idea of this problem and give you some ideas on how to solve it. :-)– Luiz Felipe
But in my case Luiz do not need tie... the value is already in an element. I did not understand.
– Davi Assumpcao
He meant that your function expects a string, but you’re passing a list of DOM elements.
– bfavaretto