Reputation: 31
Hey I am trying to concatenate strings with javascript but I am having errors. Here is my code:
function popForm(){
var v = document.getElementById('a1').innerHTML;
document.getElementById("a1_i").innerHTML =
"<input type='text' name='a1_i' value="+v+" />";
}
The element a1_i is a span that I am populating with the input tag shown above.
Further down I edit the element with ID a1:
document.getElementById("a1").innerHTML="blah bloop";
However when I try to view the result, all I can see is blah, not bloop.
Any suggestions?
Upvotes: 3
Views: 3256
Reputation: 6089
If you take a look at the generated HTML, you can notice following:
<input type='text' name='a1_i' value=blah bloop />
As syntax highlighter suggests, value of the value
attribute is blah
, while bloop is another attribute. You just need to add quotes:
function popForm(){
var v = document.getElementById('a1').innerHTML;
document.getElementById("a1_i").innerHTML="<input type='text' name='a1_i' value='" + v + "' />";
}
But if v
contains symbol '
, then you're in trouble again. So you either should replace them with HTML entities or follow jbabey's advice.
Upvotes: 3
Reputation: 674
I concur with Jbabey, it will save you extra coding of text/html strings (error prone) in the future. JavaScript concatenation is pretty straight forward
*variable1 + "Text, note quotes around" + variablearray[1] + "etc...";*
Use the methods: document.createElement document.createTextNode appendChild
https://developer.mozilla.org/en-US/docs/DOM/document.createElement https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
Upvotes: 1