2014-02-27 26 views
0

下面的JavaScript代碼通過其IP檢測用戶的國家:傳遞一個javascript變量成輸入文本

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

在我試圖讓該國的名稱,並將其傳遞給輸入第二個腳本對應的國家屬性文字:

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

但這是行不通的。任何想法如何解決我的代碼?

回答

1

你的語法設定值不正確。 value爲你分配一個屬性,而不是你調用一個函數,所以它應該是:

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

你要麼需要把這個腳本country元素之後,或者在window.onload處理程序運行:

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

FIDDLE

+0

即使你的代碼我無法得到的變量國家進入inputText –

+0

即使你把這個腳本放在'country'元素之後? – Barmar

+0

你可以看看編輯過的問題嗎? –

0

,你需要通過PARAMATERS/jQuery來添加到文本框中

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

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

你必須把JavaScript部分在HTML文件年底或文檔準備事件執行此部分,使用jQuery你可以使用$(document).ready(function...);

相關問題