Pass variable javascript to Django Form

Asked

Viewed 448 times

2

I have a Django form with this "Linked Exam" field that works as follows: The user clicks on Select Exam, goes to another window in which selects an existing exam, and with it returns to the creation page so that the url informs the exam that was selected (ex: http://127.0.0.1:8000/exam/create?exam_index=23201 indicates that the 23201 exam has been selected and must be linked).

Field

Thus, I would like, when returning to the screen with the selected exam, to display this id in the field (currently, if I type a value and click save works, what is missing and what to fill).

I can also get this id as follows:

var param = /exam_index=([^&#=]*)/.exec(window.location.search);
var exam_id = param[1];

I tried to use "getElementById" but I’m not getting it:

<div class="eight wide field" id="linked-exam-field">
                <label> Exame Vinculado</label>
                    {{form.linked_exam}}
                <a id="select-linked-exam" href = "/exam/search">
                     <i class="add square icon"></i>Selecionar Exame
                </a>
                <script>
                    var param = /exam_index=([^&#=]*)/.exec(window.location.search);
                    var exam_id = param[1];
                    console.log(exam_id);
                    //document.write(exam_id);
                    document.getElementById("linked-exam-field").value = exam_id;

                </script>
</div>

How can I do that?

  • Where is the input with the id linked-exam-field? You’re picking up the div? I don’t quite understand.

  • You’re offering too little for anyone to try to help, see if you can create a minimum, complete and verifiable example, making this effort, it is very likely that you yourself solve your problem, ah! take a look at the end of that answer, at the links.

1 answer

1

In Html:

<div id="linked_exam">{{form.linked_exam}}</div>

In the script:

document.getElementById("linked_exam").innerText = exam_id;

First: in your code you are capturing the label instead of the field itself, then to get the field, a tag was put quanquer and put the id so that js get the correct object. If you kept taking the label, the script code would override the label. Second: Your js code was almost right, the logic that remains to be understood is the following: getElementX takes the full html element, that is, it uses X to find the element you want but it returns attributes, values, class, name and etc... The use of console.log is a great ally to understand and select the element you want to work, in your case that is to write inside html, the element that almost always works is "innerText", but there are other options like "innerHtml", will depend a lot on how it was done, rendered the html.

  • Consider adding a brief explanation to your solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.