From the look of things, it doesn't seem like I'm left with much options here expect using a monospace font as suggested by Andreas. However, given that the interface I'm using doesn't allow me control over fonts, I guess this would be undoable??
================================================================
I'm required to format a string to appear as a table. It will purely be text (not even RTF). The end result is that this will be populated in a textarea in a form. So far I've the following:
var content = [
{ columnName: 'Date of Birth:', value: '11/26/1994', 'editable':'N'},
{ columnName: 'Name:', value: 'Lewis Menelaws', 'editable':'Y'},
{ columnName: 'Address:', value: '123 Apple Road', 'editable':'N'}
];
function padEnd(str){
var size = 20;
while(str.length < size){
str += " ";
}
return str;
}
var str = "";
for(var key in content)
{
var obj = content[key];
str += padEnd(obj.columnName);
str += padEnd(obj.value);
str += obj.editable;
str += "\n";
}
alert(str);
The result is as follows:
Expectation is as follows:
Any suggestions?
PS: Strangely, if I console.log(str), it appears well formatted in browser console. But I guess the format in which I'm seeing it in alert box is how it will get populated in the textarea.
JSFiddle for playing around
Probably not the best approach, but you can play around with measuring text width in a dynamically created invisible helper div. Then based on this, you can kind of calculate the required amount of spaces.
For example a simple measureText function could look like this.
function measureText(text) {
var fontSize = 12;
var test = document.getElementById("text-measure-helper");
if (!test) {
test = document.createElement("div");
test.id = "text-measure-helper"
test.style.position = "absolute";
test.style.visibility = "hidden";
test.style.width = "auto";
test.style.height = "auto";
test.style.whiteSpace = "nowrap";
document.body.appendChild(test);
}
test.innerHTML = text;
test.style.fontSize = fontSize;
return test.clientWidth + 1;
}
Not perfect though in this form, still there is some slight mis-alignment, but maybe you can tweak it to get an acceptable end result.
Have you given a thought about custom AlertBox through some of the framework you are using in your project, with inbuilt alert it seems not possible.