getting value from js in html to view.py

Hi,

I have the following code in html:

<center><h3>Coding Shortcut</h3></center>
<br/>

{% for data in userData %}

<div class="container">
  <h3>{{data.code_title}}</h3><br/>
  <textarea id = "{{data.code_title}}" readonly rows="4" cols="50">{{data.code_details}}</textarea>
  <div class="vertical-center">
    <form method="POST">
      {% csrf_token %}
    <button onclick="myFunction('{{data.code_title}}')">Copy text</button>
    </form>
  </div>
</div>

{% endfor %}

  <script>
  
  function myFunction(num) {
    // Get the text field

    var copyText = document.getElementById(num)

    // Select the text field
    copyText.select();
    copyText.setSelectionRange(0, 99999); // For mobile devices
    // Copy the text inside the text field
    navigator.clipboard.writeText(copyText.value);
  }

i want to use the variable in the function in view.py. the variable name is copyText. How to do that?

If you’re looking to add that variable to the data being submitted with the form, then you have a couple of options.

  • You could create a hidden field in the form and set the value of that field to the value you wish to include.

  • Or, if you’re sending the data in by an AJAX call, you could modify the POST data directly.
    The specifics for this would depend upon what (if any) JavaScript frameworks you may be using.

Either way, the method you choose is going to depend in part upon how you’re submitting the data from the form. (Keep in mind that views are only executed upon a request being made.)

how to reference the id from html element when the id is unique and it is from a for loop for a field in the db?

<textarea hidden id = "{{data.code_title}}"

how to get the value of that?

Your JavaScript code that you need to write is what is going to set the value of that field.

To clarify what I wrote earlier:

This is code that you need to write. Based on whatever event is going to trigger this activity, you need to set the value of this new field from your JavaScript function.