简体   繁体   中英

Javascript + Django, simple calculation not working

I need to make a simple division between two numbers for more than 100 items in a list of variables,

Inside the loop the HTML looks something like:

<input id="box1{{ item.0 }}" type="text" onkeyup="calculate()" />
<input id="box2{{ item.0 }}" type="text" onkeyup="calculate()" value="{{ item.7 }}"/>
<input id="result{{ item.0 }}" />

And my script

function calculate(){
    console.log(1);
    var myBox1 = document.getElementById('box1{{ item.0 }}').value;
    var myBox2 = document.getElementById('box2{{ item.0 }}').defaultValue;
    var result = document.getElementById('result{{ item.0 }}');
    var myResult = myBox1 / myBox2;
    result.value = myResult;}

For some reason I can't get this to work inside the loop, the script is inside the loop for each item in my list, maybe it is because JS can't capture the jinja variable {{ item }} ?

So... It works now, I know that this is not the best solution but here it is:

        <input id="box1{{ item.0 }}" type="text" onkeyup="calculate{{item.0}}()" />
        <input id="box2{{ item.0 }}" type="text" onkeyup="calculate{{item.0}}()" value="{{ item.7 }}"/>
        <input id="result{{ item.0 }}" />

        <script>
        function calculate{{coin.0}}(){
        console.log("{{ item.0 }}");
        var myBox1 = document.getElementById('box1{{ item.0 }}').value;
        var myBox2 = document.getElementById('box2{{ item.0 }}').defaultValue;
        var result = document.getElementById('result{{ item.0 }}');
        var myResult = myBox1 / myBox2;
        result.value = myResult;}
        </script>

I changed function calculate() to function calculate{{item.0}}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM