How to get data from a tag and calculate?

8

I have a jquery question. Is it possible for me to get a value inside a <span></span> tag that in this case would be an ex:%. 5% and make the calculation of a discount on a value?

Example:

Iwanttogetthe5%valuethatisinthe<span>tag,subtractbytheproductvalueanddisplaytheupdatedvalueoftheproduct.CanyoudothisviajQuery?

HTMLthatgeneratestheshelf:

  #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
    
asked by anonymous 15.09.2015 / 14:23

3 answers

3

In the question image 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 by making replace changing , to .

     

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>Calculardescontousandovalorcontidonotexto</p><divclass="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>
    
10.10.2017 / 15:04
2

You can do this, but it is not recommended to do this all in javascript.

This has a business rule face and business rules should not be exposed like this in javascript.

But, come on.

To get any text from any tag in jQuery you should do so.

$('span').text()

This returns the text of the tag.

To manipulate the value of the product is the same principle.

Take a look at the jQuery selectors.

link

Edited

Now that you've posted html it helps a lot.

To edit the value, take the class.

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

Edited

Here's an example of how to do this without messing with html or component-generation logic, but it would be MUCH better and MUCH safer to change as the rebate is calculated before being displayed in HTML.

I've taken 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

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 strongly recommend STRONGLY that this discount calculation is not done only in javascript by manipulating HTML tags.

    
15.09.2015 / 15:10
2

Basically you can do hidden fields with the desired variables, so I realized you need the price of the product and the amount 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 clear):

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

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

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

or

document.getElementsByClassName("qd_saveAmountPercent").value = desconto;
    
15.09.2015 / 15:35