3

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?

2
  • 5
    You should be using DOM methods such as createElement and appendChild to build HTML, not string concatenation. Commented Mar 1, 2013 at 20:10
  • That's the general consensus I have gotten from looking up stuff online. This is just for a little project between me and my friends though so I didn't want to put time into it to learn something else. I figured out that I just missed some quotes though. Thanks! Commented Mar 1, 2013 at 20:28

2 Answers 2

3

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.

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

Comments

1

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

Comments

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.