2013-05-29 74 views
0

我有一個PHP函數來從數據庫檢索到的數據創建一個地址。我想要使​​用相同的功能來創建一個JavaScript函數來執行相同的操作。它所做的是採取領域,如果它是空的,它什麼都不做,但如果有數據,它會附加「,」一個逗號和空格。我想把這個php函數轉換成javascript函數

$parts = array(
      $club['clubAdd1'], 
      $club['clubAdd2'], 
      $club['clubCity'], 
      $club['clubCounty'], 
      $club['clubPostcode'], 
     ); 

$address = array(); 

foreach ($parts as $part){ 
    if ('' != $part){ 
     $address[] = $part; 
    } 
} 

$address = implode(', ', $address); 

我的當前的嘗試是每次被調用的函數的KEYUP上表單字段預成形(測試目的)

function autoAddress(){ 
var address = ""; 
var address1 = document.address.address1.value; 
var address2 = document.address.address2.value; 
var city = document.address.city.value; 
var county = document.address.county.value; 
var postcode = document.address.postcode.value; 

var parts = new array[ 
     address1, 
     address2, 
     city, 
     county, 
     postcode 
     ]; 
var testAddress = new array(); 
foreach(parts as part){ 
    if ('' != part){ 
    testAddress[] = part; 
    } 
} 
testAddress = array.join(', ', testAddress); 
alert(testAddress); 

}

+4

JavaScript使用[Array.join] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)來執行PHP中的'implode'功能。否則,只需使用'+'連接字符串 – Blazemonger

+0

我不是100%確定的,但我認爲你的最後一個變量不需要逗號。 '$ club ['clubPostcode'],'嘗試刪除逗號。 –

+0

到目前爲止你的嘗試是什麼?我沒有看到任何JavaScript代碼 – rednaw

回答

1
var parts = [ 
      club['clubAdd1'], 
      club['clubAdd2'], 
      club['clubCity'], 
      club['clubCounty'], 
      club['clubPostcode'] 
     ]; 

var address = []; 

for (var i=0; i<=parts.length; i++){ 
    if (parts[i]){ 
     address.push(parts[i]); 
    } 
} 

var joined = address.join(', '); 
+0

對不起,這並不工作,舊的不工作 –

+0

是的,我編了幾次,但現在應該沒問題。 – Ziarno

+2

'var joined = address.join(',',address);'? 'join'只使用一個參數。 – meagar