How to compare the value within a <span></span> and trigger an action?

Asked

Viewed 138 times

1

How to get the value within this span?

<span id="Preço">199,00</span>

I need to compare it to another, so it fires an action when it’s over 199.00.

1 answer

2


With jQuery you can test this way:

if( parseInt( $('#Preco').text() ) > 199 )

With Pure JS, you can test like this:

if( parseInt( document.getElementById('preco').innerHTML ) > 199 )

But be careful with the pennies. As mentioned by @bfavaretto, if you have 199,50 the result will not be expected as the decimal in JS is separated by .. The solution would be to exchange the , for . and use parseFloat():

var preco = $('#Preco').text();
preco = parseFloat( preco.replace( '.', '' ).replace( ',', '.' ) ); // solução do @bfavaretto
if( preco > 199 ) { ...

Another thing: prefer not to use accentuation in the elements Ids, to avoid bugs and miscellaneous incompatibilities.


Demo:

var preco = $('#Preco').text();
preco = parseFloat( preco.replace( '.', '' ).replace( ',', '.' ) );
if( preco > 199 ) {
  $('#Res').text( 'Mais que 199' );
} else {
  $('#Res').text( 'Menor ou igual a 199' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<span id="Preco">199,50</span>
<span id="Res"></span>

  • @Gladson Links of interest: Sandbox for testing: http://jsfiddle.net/3pyt8hkd/ - Community FAQ: http://meta.pt.stackoverflow.com/q/699 - and welcome to Sopt!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.