Jerry2
Jerry2

Reputation: 3085

Jquery append to selector adding variable possible?

I have code:

<p>aaa</p>
<p>bbb</p>
<p>ccc</p>

I would like to preprend a checkbox to every paragraph with:

$("p").prepend("<input type='checkbox' name='xxx' id='xxx' /><label for='test'>xxx</label></span>");

but instead of xxx I would need to enter some variable, like counter: var1, var2, var3... How do I do that?

Upvotes: 0

Views: 42

Answers (3)

miroslav licko
miroslav licko

Reputation: 81

You search probably for so called "Template literals (Template strings)"

See please following snippet for an example of the usage.

For more information see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

// $("p").prepend("<input type='checkbox' name='xxx' id='xxx' /><label for='test'>xxx</label></span>");

//let tmp = "<input type='checkbox' name='xxx' id='xxx' /><label for='test'>xxx</label></span>";



$("p").each(function( index ) {

   let name = `name_${index}`;
   let id =  `id_${index}`;
   let text = `${$(this).text()} ${index}`

   let output = `<input type='checkbox' name='${name}' id='${id}' /><label for='${name}'>${text}</label></span>`;
  
  console.log(output);
  $(this).html(output);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>aaa</p>
<p>bbb</p>
<p>ccc</p>

Upvotes: 1

Agustin L. Lacuara
Agustin L. Lacuara

Reputation: 339

Try creating a string variable at first place in which you define the xxx variable value correctly, then use that string variable into the prepend! It should work fine

[edit]

const newXXX = "<input type='checkbox' name=" + 'xxx new value' + " id='xxx' /><label for='test'>xxx</label></span>"

$("p").prepend(newXXX)

You can use the any string concat method

Upvotes: 0

dev_in_progress
dev_in_progress

Reputation: 2494

Use prepend as function:

$("p").prepend(function(index, htmlContent) {
    console.log(htmlContent); //aaa, bbb, ccc -> the content of selected element
    return "<input type='checkbox' name='xxx' id='"+index+"' /><label for='test'>xxx</label></span>";
});

Upvotes: 2

Related Questions