I’m looking for a way to send some hidden form-data to a Django-server, which works out fine as long is a keep the javascript and the html(template) in the same file, but now i’m trying to separate them.
Probably really simple, but i guess all i have to do is get(set?) the ‘name’ of the window/html-and access it from the javascript module?
HTML:
<html>
<head>
<script src="/media/postIt.js"></script>
</head>
<body>
<form action="" method="post" id="postForm">{% csrf_token %}
<input type="hidden" id="scoreField1" name="score1"></input>
<input type="hidden" id="scoreFieldSet1" name="score1Set"></input>
<input type="hidden" id="scoreField2" name="score2"></input>
<input type="hidden" id="scoreFieldSet2" name="score2Set"></input>
<input type="hidden" id="scoreField3" name="score3"></input>
<input type="hidden" id="scoreFieldSet3" name="score3Set"></input>
</form>
<table>
<tr>
<td id="bg1" onclick="postIt('score1')">
Ones
</td>
<td id="bg1_1">
</td>
</tr>
<tr>
<td id="bg2" onclick="postIt('score2')">
Twos
</td>
<td id="bg2_1">
</td>
</tr>
</table>
Javascript:
function postIt(x){
var pointArray = [d1,d2,d3,d4,d5];
var totVal = d1+d2+d3+d4+d5;
pointArray.sort(function(a,b){return a-b});
alert(pointArray);
alert("total value: " + totVal);
if(x == "score2"){
if("{{ res.score2Set }}" == 0){
var form = document.getElementById('postForm');
document.getElementById('scoreField1').value = score1;
document.getElementById('scoreFieldSet1').value = score1Set;
document.getElementById('scoreField2').value = score;
document.getElementById('scoreFieldSet2').value = 1;
document.getElementById('scoreField3').value = score3;
document.getElementById('scoreFieldSet3').value = score3Set;
form.submit();
}
}
Edit:
Clarifying:
I can’t reach the elements in the html ‘document’ by just calling document.getElement… since they now are in different documents (physically..). I guess i’ll have to assign a name/variable to the document, somehow.
And the call it like:
nameOfDocument.getElement..
and so on..
I would guess that the line
is the problem – an included Javascript file will not go through the Django template loader, so you cannot place variables inside it. This conditional will always evaluate to false.
You need to set the variable in the template file in some manner and then retrieve it in the Javascript. The best way to do this would be probably be to add
res.score2Setas an additional argument to the postIt() function, and then do:Although obviously I don’t really know what your application does so this might not be applicable. If
res.score2Setis used elsewhere in the HTML it might be better to load it in from the DOM in the Javascript.