簡體   English   中英

從 JS 腳本中獲取值並將其傳遞給 HTML 表單

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

我不知道如何從 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 文件有一個電話號碼,您希望它出現在您的輸入字段中。 如果是這樣,那么您可以執行以下操作:

#Step 1:將電話號碼值存儲在一個變量中(例如: var mobile='myNumber';

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

好吧,以防誤解,這里有一個 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM