Home > Net >  JS & Django- How to access a value from H1 tag using DOM? I am getting no response from the JS
JS & Django- How to access a value from H1 tag using DOM? I am getting no response from the JS

Time:06-16

I am passing an integer value to HTML template, and I want to access it before it is shown to the user. Here's the code:

status.html

<div id="frame_body">
                <div id="percentage"><h1 id="receivedVal">{{projects.phase}}<sup>%</sup></h1></div>
                <div id="proj-name"><p>XXXXXXXXXXX</p></div>
                <div id="name-of-staff-head"><p>Supervised by Mr. X</p></div>
                <div id="temporary">
                    <!-- <p>Status -{{projects.status}}</p> <br>
                    <p>Phase -{{projects.phase}}</p> <br>
                    <p>Collaborators -{{projects.collab}}</p>  -->
                </div>
            </div>

JS:

function showPercentage(){
            var phase_no = document.getElementById("receivedVal").value;

            var percentage = (phase_no / 10) * 100;

            document.getElementById("receivedVal").innerHTML = percentage;
}

As you can see from the code, I want to perform that calculation and return new value there again. How can I do that?

CodePudding user response:

Add a model property to calculate values before sending them to the frontends.

class Project(models.Model):
    ...
    phase = models.CharField(max_length=100,null=True, choices=PHASE)
    ...

    @property
    def phase_percentage(self):
        return self.phase * 10

Then in your template, access it like any other value:

{{ projects.phase_percentage }}
  • Related