【问题标题】:Get a value from a JS script and pass it to a HTML Form从 JS 脚本中获取值并将其传递给 HTML 表单
【发布时间】:2021-10-01 10:59:11
【问题描述】:

我不知道如何从 js 脚本输入中获取值(用户输入的电话号码,以及脚本自动输入的国家/地区前缀代码)

  <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">

完整代码:

<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>

【问题讨论】:

  • 嗨!明确一点:你想用 JS 从字段中获取输入值吗?
  • 是的。并进入我的表单,当有人点击注册按钮时,来自 JS 字段的值进入

标签: javascript html jquery django


【解决方案1】:

据我所知,您的 js 文件有一个电话号码,并且您希望它出现在您的输入字段中。如果是这样,那么你可以这样做:

#第 1 步: 将电话号码值存储在变量中(例如:var mobile='myNumber';

#第 2 步: 现在你可以在 DOM 中的任何地方使用这个变量了。

<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>

提示:您也可以使用type="hidden" 对用户隐藏此字段。

这是一个工作示例:https://www.w3schools.com/code/tryit.asp?filename=GSTEVYR70G0L

【讨论】:

    【解决方案2】:

    好吧,如果有误会,这里有一个例子,用于 jQuery 中的 SET 和 GET 值。

    <form id="form1">
      <input id="phone_number" type="text">
    </form>
    
    <script>
    
      var phoneNumber = "123456789"; //this is your pre-defined variable
      
      $(document).ready(function(){
        //if you want to SET an input field value, you can do as the following
        $("#phone_number").val(phoneNumber);
        
        //if you want to GET an input field value, you can do as the following
        var input_phoneNumber = $("#phone_number").val();
    
        //if you want it to happen on Register button click, do this:
        $(".btn-register").click(function(){
           $("input[type='tel']").val(phoneNumber)
        })
      })
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 2018-03-22
      • 2022-11-05
      • 2018-10-11
      • 2017-02-12
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      相关资源
      最近更新 更多