jsjq-finder
jsjq-finder

Reputation: 165

How to add label for input field using before and after jquery?

I want to add a label before and after the input field. I need this result.

`<label class="containertitle">
<input id="button" type="checkbox" name="AllSalesArea"  >
<span class="checkmarktitle"></span>
</label>`

but I received an output like this.

<label class="containertitle"></label>
<input id="button" type="checkbox" name="AllSalesArea">
<span class="checkmarktitle"></span>

This is my code. I need the label close tag at the end of the span.

<input id="button" type="checkbox" name="AllSalesArea"  >


$('input[name="AllSalesArea"]').before('<label class="containertitle'>)
$('input[name="AllSalesArea"]').after('<span class="checkmarktitle"></span></label>')

Upvotes: 0

Views: 5004

Answers (3)

guradio
guradio

Reputation: 15555

  1. Add a class to both input and span and use .wrapAll()

    Description: Wrap an HTML structure around all elements in the set of matched elements.

$(".wrap").wrapAll("<label class=containertitle'></label>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="button" type="checkbox" name="AllSalesArea"  class="wrap">
<span class="checkmarktitle wrap"></span>

Upvotes: 0

jsjq-finder
jsjq-finder

Reputation: 165

Thanks to @freedomn-m.

$('input[name="AllSalesArea"]' ).wrap( '<label class="containertitle"></label>' );
$('input[name="AllSalesArea"]').after('<span class="checkmarktitle"></span>');

Upvotes: 0

Youp Bernoulli
Youp Bernoulli

Reputation: 5635

You need to do it like so:

<input id="button" type="checkbox" name="AllSalesArea"  >

$(document).append('<label class="containertitle'>).append($('input[name="AllSalesArea"]'))
$('input[name="AllSalesArea"]').after('<span class="checkmarktitle"></span></label>')

So you append a new element (<label class="containertitle'>) to the document (or a more specific element in your layout I expect) and to this label you append the already existing input element ($('input[name="AllSalesArea"]')). Then after the input element you add the <span class="checkmarktitle">

Upvotes: 0

Related Questions