user2596635 user2596635 -4 years ago 91
HTML Question

How to pull an value (number) and divide it by another number?

I have a website that I'm working on and there needs to be a bit of jquery added that will pull the value out of a raised paragraph tag, and divide it by 5, and then display that value below the original paragraph tag. I've been searching for some helpful code and I think I've found the right technique but when I put it in the code it returns nothing and I haven't been able to figure out why (novice with jquery)

the HTML set up is fairly simple -

<div>
<p class="raised">$100</p>
<p class="votes"><!--this is where I'd like the output--></p>
</div>


From searching around on google this code seems to be the most logical (to me) -

var num1 = $("p.raised").val(),
num2 = 5,
result = parseInt(num1, 10) / parseInt(num2, 10);
$(".votes").append(result);


But when I try this the number in the raised tag isn't gathered by the .val() call and nothing else works (might be because of the $ symbol?), can someone help lead me in the right direction?

Answer Source

Just change val() to text(). val() get a tag's value. But what you want is the content of the paragraph. So that's text(). html() also works. But you have to get rid of the first character of num1. Here:

var num1 = $("p.raised").text().substring(1),
    num2 = 5,
    result = parseInt(num1, 10) / parseInt(num2, 10);
$(".votes").text(result);
<div>
 <p class="raised">$100</p>
 <p class="votes"><!--this is where I'd like the output--></p>
</div>
<script
		  src="https://code.jquery.com/jquery-3.2.1.min.js"
		  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
		  crossorigin="anonymous"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download