Richerd fuld
Richerd fuld

Reputation: 384

Add chosen after adding id by dynamically

I am showing option with chosen plugin and latter add option to it.

I am trying below

<select id='one'>
    <option>a</option>
    <option>b</option>
</select>

and calling chosen plugin

$('#one').chosen();

it working fine now i am remove chosen part and adding new option to select box

$('#one').append(' <option>g</option>');
$('#one').addClass('abc').attr('id', '');
$('#one_chosen').remove();
$('.abc').attr('id', 'myid');
$('#myid').chosen();

as you can see that i have added id by class and calling chosen() on it but this time its not working. And i can not keep id one in select box if there is no chosen

jsfiddle

Upvotes: 0

Views: 606

Answers (2)

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8122

i am not sure i understand your question. But you can refresh chosen with .trigger("chosen:updated"); i.e you can do something like

 $('.select-chosen').chosen();
 $('#one').addClass('abc').attr('id', '');

 $('.abc').attr('id', 'myid');

 $('.select-chosen').trigger("chosen:updated");

Update:

Ideally, if you want to fully change the select chosen, it is better to just hide and show new select chosen. In case, if you want to add or remove option from select and want to gain fully functionality of chosen you can do it easily with

// add custom option
$(".select-chosen").append('<option>Custom Option</option>');

// remove existing option
$(".select-chosen option[value='a']").remove();

Refer : http://jsfiddle.net/qubkhtsc/5/

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

You must clone the element in order to make it work:

$('#one').chosen();

$('#one').find('option:first').remove();

$myid = $('#one').clone().attr('id', 'myid').insertBefore('#one');

$("#one, #one_chosen").remove();

$myid.show().chosen();

Updated demo

Upvotes: 1

Related Questions