Duc Doan
Duc Doan

Reputation: 415

Dynamic select option using select2 not working

In my page, I have one select option using select2 and a button to dynamic add new select option to the page. But I have a problem with new control that is created dynamically by the button, I can't select it anymore like the original control. I'm still trying to solve it but it could be great if you give me a hand, thank in advance!

<html>
<head>
	<title></title>
	<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
	<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
	<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
	<script type="text/javascript">
	jQuery( function( $ )
	{
		var $body = $( 'body' );

		$( '.sl-select' ).select2();

		$body.on( 'click', '.add-report', function()
		{
			var $this = $( this ),
				$clone = $this.siblings( '.report:last' ).clone();

			$clone.insertBefore( $this );
		} );
	} );
	</script>
</head>
<body>
	<div class="report">
		<select class="sl-select">
			<option value="1">option 1</option>
			<option value="2">option 2</option>
			<option value="3">option 3</option>
		</select>
	</div>
	<button class="add-report">Add Report</button>
</body>
</html>

Here is my fiddle

Upvotes: 1

Views: 2015

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

A better solution will be to clone the first element before, then after each append we reinitiate the select2 plugin

var $body = $( 'body' );
var $clone = '<div class="report"><select class="sl-select"><option value="1">option 1</option><option value="2">option 2</option><option value="3">option 3</option></select></div>'
    $( '.sl-select' ).select2();

    $body.on( 'click', '.add-report', function()
    {

      var $this = $( this );
    $body.prepend($clone);


    $( '.sl-select:first').select2();
    } );

Upvotes: 1

Related Questions