Hello, when you click the edit button, I create a new cancel button, but this cancel button is created every time you click on edit, how to avoid it, so that the cancel button is created only once

$(function() { $(document).on('click', '.btn_edit', function (e) { e.preventDefault(); var url = $(this).attr('data-url'); if(url == 'UPDEducation') { $('button#education').attr('data-url', 'UPDEducation'); $('button#education').text('<?=$text_save?>'); $('<button/>', { text: '', id: 'clear_fields_education', class: 'clear_fields btn btn-default get pull-right' }).appendTo('#education fieldset legend'); $('input#id_education').val($(this).attr('data')); $('input#date_of_the_beginning').val($('#'+$(this).attr('data')+' #td_date_of_the_beginning').text()); $('input#end_date').val($('#'+$(this).attr('data')+' #td_end_date').text()); $('input#education_received').val($('#'+$(this).attr('data')+' #td_education_received').text()); $('input#specialty').val($('#'+$(this).attr('data')+' #td_specialty').text()); $('input#educational_institution').val($('#'+$(this).attr('data')+' #td_educational_institution').text()); } }) ; }) ; 

Cancel button that should be created only once when you click on the kn. edit

  $(function() { $(document).on('click', '#clear_fields_education', function (e) { e.preventDefault(); $('button#education').attr('data-url', 'NewEducation'); $('button#education').text('<?=$text_add?>'); $('input#id_education').val(''); $('input#date_of_the_beginning').val(''); $('input#end_date').val(''); $('input#education_received').val(''); $('input#specialty').val(''); $('input#educational_institution').val(''); $('#clear_fields_education').remove(); }); }); 

    2 answers 2

    You can create a global variable.

     var buttonCteated = false; 

    Then, when creating the button, check

     if (!buttonCreated) { create_button(); buttonCreated = true; } 
    • Where to create a global variable? Before the two functions? - user190950
    • to answer your question you need to understand what a global variable is - Roman C

    Place item

     <button id="clear_fields_education" class="clear_fields btn btn-default get pull-right" type="button" style="display:none;"></button> 

    Markup is initially inside the '#education fieldset legend' and do:

     $('#clear_fields_education').show(); $('#clear_fields_education').hide(); 

    in the right places instead of appendTo and remove .

    Or

     if ($("#clear_fields_education").length == 0) { $('<button/>', { text: '', id: 'clear_fields_education', class: 'clear_fields btn btn-default get pull-right' }).appendTo('#education fieldset legend'); }