BlowFish BlowFish - 2 months ago 22
jQuery Question

Select2 Tags replace spaces with underscores

I have a select2 JavaScript that does my tags. The client decided that they wanted to have a space. As you know spaces ruin everything so we compromised with an underscore but we wanted to replace all spaces with an underscore just in case not everyone follows instructions.
So I added a little JavaScript, but when I save new values to their assigned attributes select2 breaks, and it seems to be two lines of code that is breaking the process.

Is there any other way to write these two lines?

My JavaScript (I will mark the ones that are messing up the program))

<script>

$("#tags").select2({
placeholder: "Add Tag(s)...",
tags: true
});

$('#tags').change(function() {
var self = this;
$(self).find('option').each(function() {
var value = $(this).val();
var text = $(this).text();
var newValue = value.split(' ').join('_');
var newText = text.split(' ').join('_');
$(this).val(newValue); // This line overrides the tag manually input before it.
$(this).text(newText);
$('.select2-selection__choice').each(function() {
var title = $(this).attr('title');
var newTitle = title.split(' ').join('_');
$(this).val(newTitle)
$(this).text(newTitle); //This line deletes the x in the tags
});
});
});
});
</script>

Answer

If you need to change the text and value on select field change, you can do it like this:

$(function(){
  $('#tags').change(function() {
      $(this).find('option').each(function() {
          var value = $(this).val();
          var text = $(this).text();
          $(this).val(value.split(' ').join('_'))
          $(this).text(text.split(' ').join('_'))
      });
  });
});

Here's a plunkr demo