How to take data from a tag and calculate?

Asked

Viewed 1,426 times

8

It is possible I get a value within a tag <span></span>? Ex: <span> 5% </span> and calculate a discount at a value?

Example:

Cálculo Porcentagem

I want to get the value of 5% that is in the tag <span>, subtract by product value and display the updated product value. You can do this with jQuery?

My code:

  #set($id = $product.Id)
#set($uri = $product.Uri)
#set($escapedName = $product.HtmlEscapedName)
#set($evaluationRate = $product.EvaluationRate) 

<!-- class: shelf prateleira vitrine home -->
<div class="shelfImageWrapper">
    <div class="shelfButtonWrapper">
        <div class="shelfAmountInCart">
            $product.AmountInCart
        </div>
        <!--<div class="shelfBuyButtomWrapper">
            $product.BottomBuyAsynchronous
        </div>-->
    </div>
    <a class="shefImage" title="$escapedName" rel="nofollow" href="$uri">
        <div class="shelfImage-1">$product.GetImageTag(235,235)</div>
    
    </a>
</div>

<div class="shelfInformationWrapper">
    <input type="hidden" value="$product.BestPrice" class="qd_productPrice" />
    <input type="hidden" value="$product.ListPrice" class="qd_productOldPrice" />
    <input type="hidden" value="$product.NumbersOfInstallment" class="qd_sp_installments" />
    <h3><a title="$escapedName" href="$uri" rel="nofollow">$product.Name</a></h3>
    #if ($product.IsInStock)
        <div class="yv-review-quickreview" value="$id"></div>
        <p class="shelfPriceWrapper">
            <a title="$escapedName" rel="nofollow" href="$uri">
                #if ($product.HasBestPrice)
                    <span class="shelfOldPriceWrapper">De $product.ListPrice</span>
                    <br/>
                #end
            Por <span class="shelfNewPriceWrapper">$product.BestPrice </span> <span>à vista</span>
                <br/>
                <span class="installmentWrapper">
                    #if ($product.NumbersOfInstallment > 1)
                        em até
                        <strong class="installment"> ${product.NumbersOfInstallment}x </strong> 
                        de
                        <strong class="InstallmentValue"> $product.InstallmentValue </strong> 
                        <span>s/juros</span>
                    #end
                </span>
                    #if ($product.HasBestPrice)
                        <span class="saveAmount">economize <span class="qd_saveAmount">R$ </span> <small>(</small><span class="qd_saveAmountPercent">%</span><small>)</small></span>
                    #end
            </a>
             $product.BottomBuyAsynchronous
        </p>
    #else
        <p class="outOfStock">Produto Indisponível</p> 
    #end
</div>
#if ($product.IsInStock)
    <div class="shelfStampsWrapper">
        <a title="Clique para ver as condições de frete" class="highlightWrapper" rel="nofollow" href="#" data-reveal-id="frete-gratis-vitrine" data-animation="fade">$product.HightLight</a>
        <a title="$escapedName" class="highlightWrapper" rel="nofollow" href="$uri">$product.DiscountHightLight</a>
    </div>
#end

  • 1

    What is this tag ? a label, a span, an input text ?

  • The tag that will have the value returned is a <span>, both tags are <span>

  • Could you post the HTML of this BOX? So we can analyze it better?

  • So, I don’t know if you will understand very well, html is based on the platform that we use here in the company to program the store, but even so I will post, I edited the question with HTML

3 answers

3

In the image of the question the span has text, so to extract only the numeric content of the string can use regular expression.

Do not forget to convert the value of the product to monetary in the international standard making replace altering , for .

Another important information is to convert the captured values to float before performing the calculation.

var price = $('#price').html().replace('R$ ', '').replace(',', '.'); //trocar , por .
var discount = $('#info').html().replace(/[^0-9]/g, ''); //replace com regex
var cal; // váriaval que retornará o calculo

cal = (parseFloat(price) - (parseFloat(price) * (parseFloat((discount)) / 100))).toFixed(2);

var total = String(cal.replace('.', ','));

$('#amount').html('R$ ' + total);
.box {
  border: 1px solid #ccc;
  max-width: 50%;
  padding: 15px;
  color: #187586;
}

#amount {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Calcular desconto usando valor contido no texto</p>
<div class="box">
  <label>
valor do Sapato:
<span id="price">R$ 199,99</span>
</label>
  <br><br>
  <label>
Informações:
<span id="info">Valores a vista tem 5% desconto</span>
</label>
</div>
<br>
<br>
<br>
<label>
valor a vista
<span id="amount"></span>
</label>

2

It has to do this yes, but it is not recommended to do all this in Javascript. This has the face of business rule, and business rules should not be exposed like this in Javascript.

But, come on. To get any text from any jQuery tag you should do so.

$('span').text()

This returns the tag text. To manipulate the product value is the same principle. Take a look at the jQuery selectors.

In your case, to edit the value, take the element class:

$('span.shelfNewPriceWrapper').text(); //pega o valor
$('span.shelfNewPriceWrapper').text(novoValor); //seta o valor

Here’s an example of how to do this without tampering with html or component generation logic - however, it would be MUCH better and MUCH safer to change how the discount is calculated before it is displayed in HTML.

I took several steps to be explanatory.

var expressaoNumero = /\d+/g; //expressão regular para pegar número

var numeros = $("p[class*='desconto-a-vista']").text().match(expressaoNumero); //retorna um array com todos os numeros que tem na string

var valorDesconto = parseFloat(numeros[0]); //aqui pega o valor do numero

var valorTexto = $("span.shelfNewPriceWrapper").text().replace('R$', '').replace(',', '.'); //pega o valor e muda para o formato americano para conversão

var valorTotal = parseFloat(valorTexto);

var valorComDesconto = (valorDesconto / 100) * valorTotal; valor calculador do desconto

Another detail, this example works only if the displayed value is in real, if it is possible to display in other currencies, dollars, euro or etc., I recommend STRONGLY that this discount calculation is not done only in Javascript manipulating HTML tags.

  • I do not know if I understood very well haha And so I need to take the value that is in the discount flag 5% and multiply the value of the price of the product that is in "green" by 0,5 to be able to display the value with the discount in sight.

  • @Can Juliosantos post the HTML of the discount tag? It is not present in the HTML you posted. Post the tag that has exactly what you want, the one that is in gray in the photo written "Cash discount 5%"

  • Hello Erick, the tag is generated by this HTML: <a title="Click to see the shipping conditions" class="highlightWrapper" rel="nofollow" href="#" data-Reveal-id="shipping-free-showcase" data-Animation="fade">$product.Hightlight</a> Plus its return is this: <p class="flag discount-a-view-5-">Cash discount 5%</p>

  • @Juliosantos see the second edition

  • Beauty ! I’m going to test ! Vlw!

2

Basically you can make hidden fields with the desired variables, so I realized you need the price of the product and the value of the discount, so it would look like this:

<input type="hidden" value="$product.BestPrice" id="productValue" />
<input type="hidden" value="$product.DiscountHightLight" id="porcentageValue" />

and then in javascript you would do so (the calculation was not clarified):

var desconto = $("#productValue").val() / $("#porcentageValue").val() * 0,5;

and then put in the field or span of that percentage:

 $(".qd_saveAmountPercent").text(desconto);

or

document.getElementsByClassName("qd_saveAmountPercent").value = desconto;
  • Beauty ! I’m going to test ! Vlw!

  • All right, I just made an edit to make sure it works.

Browser other questions tagged

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