0

I have a page where I'm displaying some number in divs. I want to add the numbers in 2 divs and I want to display the total in a 3rd div.

If I enter the below script in the developers console it works, but I'm not able to load the script into the page.

div3.innerHTML = parseInt(div1.innerHTML) + parseInt(div2.innerHTML);

jQuery approach I tried -

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function() {
  var vtotal = $('#total').text();
  var varch = $('#archTotal').text();
  var vall = $('#alltotal').text();
  vall = parseInt(vtotal) + parseInt(varch);

});
</script>
  • are you tried to use Content editor web part ? to load your scripts ? – Mohamed El-Qassas MVP Aug 2 '16 at 9:38
  • can you put your code which you have tried ? – Codec Aug 2 '16 at 9:38
  • Yes, I used CEWP to load the script. Please find the code in the post description. – Korak Aug 2 '16 at 11:05
  • jsfiddle.net/3wu6go1y – Korak Aug 2 '16 at 11:23
  • have you tried writing jQuery instead of $ character? – Gwny Aug 2 '16 at 12:52
0

Your problem is the DOM

When you execute in the console, the DOM is all built and ready to be used

If you put script on a page the page (DOM) is still loading so your DIV references are most likely undefined

You have to wait till the DOM is ready

Like jQuery does with the ready function

But you can do without jQuery: https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the

  • Hi, I tried the jQuery document ready approach, but it didn't work for me. Here's my code - <script src="ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { var vtotal = $('#total').text(); var varch = $('#archTotal').text(); var vall = $('#alltotal').text(); vall = parseInt(vtotal) + parseInt(varch); }); </script> – Korak Aug 2 '16 at 10:56
  • Sorry,I can't read jQuery.. – Danny '365CSI' Engelman Aug 2 '16 at 10:59
0

Try using window.onload()

You could be facing the case where even though the DOM has loaded, the data you want could be in a frame that hasn't loaded yet. Here is a thread that explains the difference between $(document).ready() & window.onload()

  • I have tried using window.onload(), but it didn't work. – Korak Aug 3 '16 at 10:54
  • Try changing the last line of the jQuery to $('#alltotal').text(parseInt(vtotal) + parseInt(varch)); in the current code you are not changing the third div. – Shadia Aug 3 '16 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.