I have a PHP function to create an address from the data retrieved from the database. I want to use the same feature to make a JavaScript function that will do the same. What it does is take the field and if it is empty it does nothing but if there is data then it will append ", " a comma and space.
$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);
My current attempt is the function is called everytime the keyup is preformed on the form fields (test purposes only)
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);
}
peter-b
4,2196 gold badges34 silver badges43 bronze badges
asked May 29, 2013 at 15:57
Pierce McGeough
3,1169 gold badges46 silver badges66 bronze badges
1 Answer 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(', ');
answered May 29, 2013 at 16:06
Ziarno
7,5725 gold badges37 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
user229044
var joined = address.join(', ', address);? join only uses one argument.Pierce McGeough
Thanks, works minus one thing. The comma is being appended to the end even if there is no more data. Tired it here but keyup mightnt do alerts in jsfiddle jsfiddle.net/NmSBC
Ziarno
Yeah, edited the if statement, no comma in the end now. It happened because the last value in the array parts was accually "undefined" and it WAS different then '';
default
implodedoes in PHP. Otherwise, just concatenate strings using+$club['clubPostcode'],Try removing the comma.foreach(parts as part),partwill contain a numeric index of the current entry inparts, you have to useparts[part]to access it.