Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Concatenating Strings in JavaScript

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?

like image 917
beepboop Avatar asked Aug 04 '26 00:08

beepboop


2 Answers

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.

like image 117
Artem Sobolev Avatar answered Aug 05 '26 12:08

Artem Sobolev


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

like image 34
Craig London Avatar answered Aug 05 '26 13:08

Craig London



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!