2

I am trying to create an array of simple text inputs inside an SVG that is created dynamically using javascript.

First I was doing it in PHP and there the snippet would look like this:

for ($row=0; $row<7; $row++)
{
for ($col=0; $col<7; $col++)
{
    $fx=130+100*$col;
    $fy=120+100*$row;
    echo "<foreignObject x="".$fx."" y="".$fy."" width="50" height="80">\n<body xmlns="http://www.w3.org/1999/xhtml">\n<form><input type="text" width="1"/ style="font-size:48px; border:none;"></form>\n</body>\n</foreignObject>";
}
}    

Then in javascript I would try it for a single instance like this but I did not get this to work.

var field = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
field.setAttribute("x", "130");
field.setAttribute("y", "120");
field.setAttribute("width", "50");
field.setAttribute("height", "80");
mySvg.appendChild(field.cloneNode(true));
var s = '<body xmlns="http://www.w3.org/1999/xhtml"><form><input type="text" width="1" style="font-size:48px; border:none;"></form></body>';
var s1 = document.createElement(s);
field.appendChild(s1);
</script>

Any hints? Or should I switch to a completely different implementation (e.g. CSS)?

1 Answer 1

1

document.createElement requires an element name as an argument and creates a single element, it doesn't parse arbitrary html/xml content.

You can use DOMParser to parse a string of markup.

As for the PHP you probably need to escape the internal double quotes in the echo.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I will have a look at the DOMParser. (The PHP code works for me, even with the non-escaped quotes.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.