2

I would like to create an HTML object with jQuery and set the id from a variable but I don't know how it could work.

This is the code:

countArticle=eval("Count" + x+";");
copy.css("width", "96px");
copy.find("img").css("height", "50px");
copy.append("Anzahl: <span class='count' id="countArticle" )>"+ 1
+"</span>");
copy.appendTo("#target").fadeIn();

Does anyone know, how this could work?

j08691
  • 204,283
  • 31
  • 260
  • 272

4 Answers4

2
copy.append("Anzahl: <span class='count' id='" + countArticle + "'>" + 1 + "</span>");

To concatenate strings, you use a plus sign.

So you want this string:

Anzahl: <span class='count' id='

then the value of countArticle, and then this string:

'>

Put the strings in double quotes, and you get:

"Anzahl: <span class='count' id='" +
countArticle +
"'>"

(Note that I also removed a right paren that didn't seem to belong there.)

user94559
  • 59,196
  • 6
  • 103
  • 103
2

I think you just need to use + in your 4th line:

copy.append("Anzahl: <span class='count' id='" + countArticle + "' )>" + 1
        +"</span>");
1

Have you tried doing a concatenation?

copy.append("Anzahl: <span class='count' id='" + countArticle + "' )>"+ 1
    +"</span>");
0

I generally prefer to define attributes via an object when creating elements with jQuery.

jQuery( html, attributes )

html
Type: htmlString
A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).

attributes
Type: PlainObject
An object of attributes, events, and methods to call on the newly-created element.

var $copy = jQuery('#copy'),
    countArticleID = 'countArticle',
    html = '<span />',
    attributes = {
      'id': countArticleID,
      'class': 'count',
      'text': 1
    },
    $count_element = jQuery(html, attributes);

$copy.append('Anzahl:', $count_element);
.count {
  padding: 0 .5em;
  margin: 0 0 0 .5em;
  border: 1px solid #AAA;
  border-radius: .25em;
}
#countArticle {
  background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copy"></div>

Of course, the code can be shortened if brevity is important:

var countArticleID = 'countArticle';

jQuery('#copy').append('Anzahl:', jQuery('<span/>', {
  'id': countArticleID,
  'class': 'count',
  'text': 1
}));
.count {
  padding: 0 .5em;
  margin: 0 0 0 .5em;
  border: 1px solid #AAA;
  border-radius: .25em;
}
#countArticle {
  background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copy"></div>

For further reference, see Creating a div element in jQuery.

Community
  • 1
  • 1
showdev
  • 28,454
  • 37
  • 55
  • 73