This is what I am currently doing to trim all of my value. It is ugly and a too repetitive.
var strHTML = '';
$.getJSON('info.php',
function(data) {
$.each(data, function(i, item) {
strHTML += $.trim(item.fname) +
$.trim(item.lname) +
$.trim(item.address) +
$.trim(item.phone) +
...(about 10 more of these);
});
});
There ought to be a better way to do this.
This is what I am currently doing to trim all of my value. It is ugly and a too repetitive.
var strHTML = '';
$.getJSON('info.php',
function(data) {
$.each(data, function(i, item) {
strHTML += $.trim(item.fname) +
$.trim(item.lname) +
$.trim(item.address) +
$.trim(item.phone) +
...(about 10 more of these);
});
});
There ought to be a better way to do this.
Share edited Mar 24, 2011 at 17:41 Pascal MARTIN 401k81 gold badges663 silver badges667 bronze badges asked Mar 24, 2011 at 17:36 nolabelnolabel 1,1574 gold badges18 silver badges26 bronze badges 2-
Is there no
$(item).each(function(j){ strHTML+= $.trim(this[j])}
??? – mplungjan Commented Mar 24, 2011 at 17:42 - mplungjan doesn't work. I need the flexibly to concatenate my html along with this, but I left it out b/c of the mess. – nolabel Commented Mar 24, 2011 at 22:21
3 Answers
Reset to default 1A for...in
example, with hasOwnProperty
:
var obj = {
foo: ' bar',
blahblah: ' ahahaha '
};
var arr = [];
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push($.trim(obj[key]));
}
}
alert(arr.join(','));
I'd say you should trim the data on the PHP-side, as it's your PHP script that generates it 1.
Basically : make sure your info.php
script generates correct data.
In PHP, you can use the [**`trim()`**][1] function.
And if your data is stored in an array, you can apply that function to all items of that array using the array_map()
function :
$data = array_map('trim', $data);
*As a consequence, I will add the PHP tag to this question*
If you want all properties of item to be trimmed you can use the for (props in item) {} -loop to loop through all of them. Because u can use this on all javascript-object you can create a function that does the trimming on all properties of an object.