создать кнопку сброса значения на select2

я использую select2 и пытаюсь создать кнопку сброса для каждого выбора. у меня 6 выбор.

мой скрипт такой

$('.deggre').on('change', function() {
  var deggre = $( this ).val();
  var span = $("#dropdownMenu1").find('span').clone(); // Copy 'X' span.
  $("#dropdownMenu1").text(deggre); // Insert text first.
  $("#dropdownMenu1").append(span); // Then, append the 'X' span.
  if($(this).val() == "")
    $('#dropdownMenu1').css({"display": "none"});//value is none then hide
  else
    $('#dropdownMenu1').css({"display": "inline-block"});//have value then show
});
$("#dropdownMenu1").click(function(){
  $(".deggre").val("");
});

мой скрипт не работал для этого случая. Как решить эту проблему? мне нужно показать кнопку, когда мы выбираем вариант на select2, и дать innerHtml кнопке. а затем, когда кнопка нажимается, ее собственный выбор сбрасывается, а кнопка исчезает, потому что она не получила значение.

вот мой jsfiddle https://jsfiddle.net/acvxeq8x/2/


person renat natanael    schedule 07.07.2016    source источник
comment
просто обновите описание, смотрите jsfiddle   -  person renat natanael    schedule 07.07.2016


Ответы (2)


Вам нужно запустить change

$("#dropdownMenu2").click(function(){
  $(".position").val("").trigger('change');
});

Я обновил вашу скрипку: https://jsfiddle.net/acvxeq8x/3/

person currarpickt    schedule 07.07.2016

Вот упрощенная и минимальная версия вашего code, которая довольно прямолинейна. Код ниже кажется длинным из-за комментариев, добавленных для объяснения. Надеюсь, вы проигнорируете их, как только поймете.

Изменения HTML

<div class="wrap">
   <!--Remove everything within wrap div and keep one copy of button in js to dynamically
   construct the button tag-->
</div>

Добавлен новый CSS

button.btnspl{
    margin:10px;
    /*Bit styling for dynamically created buttons*/
}

Изменения JS

//Bind single change event to all your select element
$('.deggre,.position,.year').on('change', function() {
  var ctrl=$(this); //reference for current element

  var ctrlClass=ctrl[0].classList[0]; //get the first class which will be the class given 
  //to your original select element like deggre, position, year etc.,

  $('button.btnspl[data-control="'+ctrlClass+'"]').remove();
  //Since your select element is single select type, I hope you want to keep only one tag 
  //for each select. So, you remove other tags with above line

  if(ctrl.val() == "")return; //return if value is empty, you aren't creating anything

  var btn=$('<button class="btn btn-grey btnspl" type="button"><span class="glyphicon glyphicon-remove"></span></button>');
  //Button copy from your wrap div

  var option = $('<span>'+ctrl.val()+'</span>');
  //get the selected option and place it in span

  var span = $(deggre).insertBefore(btn.find('span'));
  //insert the above created span before the glyphicon-remove in button

  btn.attr('data-control',ctrlClass);
  //the created button should have information about the control which created it
  //so wrapping the ctrlClass [deggre, year, position] into data-* attribute of created button
  //this will be used to remove particular button and clear its respective select, 
  //on different scenarios

  $('.wrap').append(btn);
  //append the button to .wrap div    
});


//attaching close click event to glyphicon-remove.
//Read about event-delegation for dynamically created elements
//button is dynamically created here
$('.wrap').on('click','.glyphicon-remove',function(){
    var ctrl=$(this).closest('.btn');
    //get the parent of the clicked remove icon using closest

    var ctrlClass=ctrl.attr('data-control');
    //get its data-control attribute added during creation

    $('.'+ctrlClass).val("").trigger('change');
    //empty its value and trigger change

    ctrl.remove();
    //remove the control
})

JSFiddle DEMO

person Guruprasad J Rao    schedule 07.07.2016