0

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?

3 Answers 3

2

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>";
});
Sign up to request clarification or add additional context in comments.

1 Comment

The first version didn't work, this version with return works, thank you so much!
1

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>

Comments

0

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

1 Comment

Hm, I am not sure if I understand, could you make me a simple example please?

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.