簡體   English   中英

將javascript變量傳遞到輸入文本

[英]pass a javascript variable into input text

以下javascript代碼通過其IP檢測用戶所在的國家/地區:

 <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
 <script language="JavaScript"> 
            document.getElementById("country").value(geoip_country_name());
 </script>
<script language="JavaScript">
  document.write(geoip_country_name());
</script>

在第二個腳本中,我試圖獲取國家/地區的名稱並將其傳遞給與country屬性對應的輸入文本:

<h:form id="newCustomerForm">
  <fieldset>
    <legend>Register Form</legend>
    <p:outputLabel  value="Country :" for="country"/>    
    <p:inputText id="country"
      value="#{customerMB.country}"
      title="Country"
      required="true"
      requiredMessage="The country field is required.">
  </fieldset>
</h:form>

更新

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
     <script language="JavaScript">  window.onload = function() {
                document.getElementById("country").value =geoip_country_name();
            };
     </script>
    <script language="JavaScript">
      document.write(geoip_country_name());
    </script>

但這是行不通的。 關於如何修正我的代碼有什么想法嗎?

您設置值的語法不正確。 value是您分配的屬性,而不是您調用的函數,因此應為:

document.getElementById("country").value = geoip_country_name();

您要么需要將此腳本放在country元素之后,要么在window.onload處理程序中運行它:

window.onload = function() {
    document.getElementById("country").value = geoip_country_name();
}

小提琴

您需要通過參數/ jQuery添加到文本框

var input = $('#yourId');
var text = input.val();
input.val(text.substring(0, 1) + '.' + text.substring(1));

問題是,您想在'country'元素存在之前加載JavaScript。

您必須將JavaScript部分放在HTML文件的末尾或在文檔准備事件中執行此部分,而使用jQuery,您可以使用$(document).ready(function ...);

暫無
暫無

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

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