The task is this: when selecting from select, select values ​​should turn into a label with text from select and next to the "Edit" button. If you click on the "Change" label and the button again turns into a select. The first transformation works, but the button does not. What am I doing wrong?

HTML:

<select id="select_customer" data-placeholder="Покупатель" tabindex="2"> <option value=""></option> <option value="United States">United States</option> <option value="United Kingdom">United Kingdom</option> <option value="Afghanistan">Afghanistan</option> </select> 

Js:

 $("#select_customer").change(function (){ var sp = $("#select_customer :selected").text(); var $span = $('<h3><span class="label label-primary">' + sp +'</span><button id="choose_customer" type="button" class="btn btn-default"> Изменить</button></h3>') $("#select_customer").select2('destroy').replaceWith($span); }); $("#choose_customer").click(function(){ $span.replaceWith($("#select_customer").select2()); }) 

;

    2 answers 2

    The problem is that the $("#choose_customer").click() event $("#choose_customer").click() assigned when creating the page when the $("#choose_customer") object does not already exist. It appears later, but the event is no longer tied to it.

    I propose to change the "callsign" buttons, as well as the event binding ...

     var $span = $('<h3><span class="label label-primary">' + sp +'</span><button type="button" class="choose_customer btn btn-default"> Изменить</button></h3>') 

    And the event is not bound to the button, but to the document.

     $("body .choose_customer").click(function(){ $span.replaceWith($("#select_customer").select2()); }); 

    Because of the select2() component, I cannot verify the accuracy of the answer, but I think I indicated the general direction of the decision :)

    • Your answer does not work, but you really pointed out the direction. thank! - Kley

    Select2 () does not matter here. it can be thrown out. I did this: 1. after loading the document I remembered select to variable

     $(document).ready(function(){ var cust=$('#select_customer'); 

    when the select is changed, a label and a button are created, the select is replaced with them, and an event is hung up on the button by the on method for which all of the replacements should be replaced with select (my cust variable).

     $("#select_customer").change(function (){ var sp = $("#select_customer :selected").text(); var $span = $('<h3><span class="label label-primary">' + sp +'</span> <button id="choose_customer" type="button" class="btn btn-default btn-sm"> Изменить</button></h3>') cust.replaceWith($span); $("#choose_customer").on('click',function(){ $span.replaceWith(cust); cust.on('change');//к селекту привязываю событие }); }); 

    because select the newly created event change is not bound to it. I'm trying to tie him. but it is not attached. The label is replaced by the back select, but when it changes, nothing happens