0

I am trying to check user input before displaying the correct HTML element.

Here is my code:

<script>
var additem = '<div><div class="itesm">' +
'<h1>'+itemname+'</h1>';
if(itype == 'edit'){
 additem .= '<div><input id="itemdis" value="'+itemdis+'"></div>';
}else{
 additem .= 'Good item';
}
 additem .= '</div>';
$('showitem').html(additem);
</script>

I always do something like this in PHP, but I can't figure out how to do it in javaScript.

Can anyone tell me how to concatenate the strings together so that my example works?

Krunal
  • 77,632
  • 48
  • 245
  • 261
Peter
  • 1,860
  • 2
  • 18
  • 47

4 Answers4

0

You can use + instead of ., check snippet below..

var itemname = "itemname",
    itemdis = "itemdis",
    itype = "edit";

var additem = '<div><div class="itesm">' +
'<h1>'+itemname+'</h1>';
if(itype == 'edit'){
 additem += '<div><input id="itemdis" value="'+itemdis+'"></div>';
}else{
 additem += 'Good item';
}
 additem += '</div>';
document.getElementById('showitem').innerHTML =  additem;
<div id="showitem"></div>
Super User
  • 9,448
  • 3
  • 31
  • 47
0

This will help you.

<script>
var additem = '<div><div class="itesm">' +
'<h1>'+itemname+'</h1>';
  if(itype == 'edit'){
   additem .= '<div><input id="itemdis" value="'+itemdis+'"></div>';
  }else{
   additem .= 'Good item';
  }
  additem .= '</div>';
  $('showitem').html(additem);
</script>

Please note javascript has + operator for concatenation.

Kirit
  • 405
  • 3
  • 18
0

var itype = 'edit';
var additem = '<div><div class="itesm"><h1>ABC</h1>';
if(itype == 'edit'){
 additem += '<div><input id="itemdis" value="ABC"></div>';
}else{
 additem += 'Good item';
}
 additem += '</div>';
$('div').html(additem);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="showtime"></div>
0

Some other users have already pointed out that javascript uses the + operator and not the . operator (like PHP does).

A more, full-fledged example can be found at w3schools.

Note that this, however, will not work right when you use numbers and strings combined. As demonstrated with the following code:

var a = 10;
var b = 20;
console.log('result is ' + a + b);

The previous code will, unlike expected, print "result is 120".

There is another, well-known, way to concat strings, however. This works by using the .concat method like so:

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2);

Interestingly you could also convert the strings to an array and use array operations like [push][2] to concatenate strings.

A performance evaluation (by jsperf) can be found here.

ps: sorry for taking so long, I forgot about this tab :)

Rick van Lieshout
  • 2,276
  • 2
  • 22
  • 39