Skip to content

Get a value from a JS script and pass it to a HTML Form

I don`t find out how to get the value from the js script input ( phone number that user input , and the country prefix code that the script auto put )

  <script src="{% static 'assets/js/intlTelInput.js' %}"></script>
  <script>
    var input = document.querySelector("#phone");
    window.intlTelInput(input, {
      initialCountry: "gb",
    });
  </script>

and have it saved thru my HTML form under this:
  <input type="tel" name="phone-number" class="form-control input-style" placeholder="your phone">
  <input type="tel" id="phone">

Full code :

<form class="submit-form" method="post" action="{% url 'register' %}" enctype="application/json">
  {% csrf_token %}

<div class="div-block">
<div class="double-fields-step-2-only">
<div class="form-group">
<div class="form-group right">
  <input type="tel" name="phone-number" class="form-control input-style" placeholder="your phone">
  <input type="tel" id="phone">

  <script src="{% static 'assets/js/intlTelInput.js' %}"></script>
  <script>
    var input = document.querySelector("#phone");
    window.intlTelInput(input, {
      initialCountry: "gb",
    });
  </script>
  <div class="icon"></div>
  </div>
</div>
<button type="submit" class="btn btn-register" data-title="Loading...">
Register
</button>
</form></div>
</form>

Answer

As I can understand, your js file has a phone number and you want it to be in your input field. If so, then you can do something like this:

#Step 1: Store the phone number value in a variable (e.g: var mobile='myNumber';)

#Step 2: Now you can use this variable inside the DOM anywhere.

<form id='myform' method="post" action="action/">
  <!--your fields here-->
</form>
<script>
 document.getElementById('myform').innerHTML+=`
  <input type="text" id="myid" name="mobile" value="${mobile}">
 `
</script>

Tip: you can also use type="hidden" for hiding this field from users.

Here is a working example: https://www.w3schools.com/code/tryit.asp?filename=GSTEVYR70G0L