0

I'm trying to change the text within a p tag on load using JavaScript, using the first character of that p tag. The p tag is populated using Flask double curly brackets syntax, i.e {{yourstring}}.

A variable is calculated in Python and either a 1 or 0 is returned and then added to a string at index 0. That string is then pulled into the HTML as the {{trailing_check}} variable.

I want my js function to change the value in that first index to say 'tick' or 'cross' (will later be an image) based on whether the value is a 1 or 0.

However, nothing seems to be happening... please see my code below.

HTML

<div class="summary" onload="good_outcome()">
   <p id = "trailing_check">{{trailing_check}}</p>
</div>

JS

function good_outcome(){
   if(document.getElementById("trailing_check").innerHTML.charAt(0) == '1'){
     document.getElementById("trailing_check").innerHTML = "tick"
   }
   else{
     document.getElementById("trailing_check").innerHTML = "Cross"
   }

What am I doing wrong?

ranieribt
  • 1,280
  • 1
  • 15
  • 33

2 Answers2

0

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there. Check this answer for details

You should add the function call to Document ready function: So your Div will not have the onload as shown below:

<div class="summary" >
   <p id = "trailing_check">{{trailing_check}}</p>
</div>

And the JS changes to run good_changes() at Document load:

`$( document ).ready(function() {
    good_outcome();
}

If you are not using the Jquery, You can also attach the same function to DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', good_outcome, false);
nircraft
  • 8,242
  • 5
  • 30
  • 46
0

Your problem is that div elements do not support the onload event. To fix this you have to run your script after the document has finished loading by listening the document DOMContentLoadedevent to know when it is loaded or just move the onload to the body element.

If using the body element just do

<body onload="good_outcome()">
   ...
</body>

And by listening the DOMContentLoaded event in JavaScript

<div class="summary">
  <p id = "trailing_check">{{trailing_check}}</p> 
</div>
<script>
  document.addEventListener("DOMContentLoaded", function(event) { 
   if(document.getElementById("trailing_check").innerHTML.charAt(0) == '1'){
     document.getElementById("trailing_check").innerHTML = "tick"
   }
   else {
     document.getElementById("trailing_check").innerHTML = "Cross"
   }
  });
</script>
Jarno Lonardi
  • 303
  • 1
  • 7