getting value from js in html to


I have the following code in html:

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

{% for data in userData %}

<div class="container">
  <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>

{% endfor %}

  function myFunction(num) {
    // Get the text field

    var copyText = document.getElementById(num)

    // Select the text field;
    copyText.setSelectionRange(0, 99999); // For mobile devices
    // Copy the text inside the text field

i want to use the variable in the function in 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.