1

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?

user2596635
  • 381
  • 1
  • 5
  • 17
  • yes it's because the `$` symbol. `parseInt("$100")` will return 0 while `parseInt("100$")` returns 100. `parseInt` parses until a non-number is reached. – Taha Paksu Mar 23 '17 at 14:41
  • Possible duplicate of [jQuery get content between
    tags](http://stackoverflow.com/questions/6854009/jquery-get-content-between-div-tags)
    – Jared Smith Mar 23 '17 at 14:41
  • What `console.log($("p.raised"))` and `console.log($("p.raised").val())` tell you? If values are correct, then continue the logic! – Fefux Mar 23 '17 at 14:42
  • Better answer: http://stackoverflow.com/questions/559112/how-to-convert-a-currency-string-to-a-double-with-jquery-or-javascript – Taha Paksu Mar 23 '17 at 14:46

2 Answers2

2

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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
0
var num1 = $(".raised").html().replace('$',''),
    num2 = 5,
    result = parseInt(num1, 10) / parseInt(num2, 10);
    console.log(result)
$(".votes").append(`$${result}`);
KornholioBeavis
  • 2,402
  • 2
  • 19
  • 26
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – manniL Mar 23 '17 at 22:17