0

I am using MagicSuggest and I need to get the length of the selections on a blur event. My code works great if I add a new selection via the ENTER key but does not work if I choose an existing selection from the list.

Use cases

  1. if User chooses suggestions via the ENTER key, length = 1 - Correct
  2. if User chooses suggestions via the MOUSE click, length = 0 - Incorrect, should be 1

JSfiddle https://jsfiddle.net/a1ejqtae/7/

HTML

<form action="">
  <label for="keyword">Keywords</label>
  <input type="text" id="keywords">
</form>

JS

$('form input').on('blur', function(){

var selectionLength = $('form .ms-sel-item').length;
$('.selection-name').text(selectionLength);
console.log('Selection is ' + selectionLength);

if( selectionLength > 0 ){
console.log('Selection is greater than 0');
}

});

PS Does anyone know what happened to this plugin, the github page is still running but the site with all documentation and examples is down - http://nicolasbize.com/magicsuggest/doc.html. Thank goodness for wayback machine.

Clinton Green
  • 9,697
  • 21
  • 68
  • 103

2 Answers2

1

I tested code below in your jsfiddle and it worked fine:

var labelName = $('label').text();
console.log('label = ' + labelName);

$('#keywords').magicSuggest({
  hideTrigger: true,
  placeholder: 'Start typing for keyword suggestions',
  useZebraStyle: true,
  data: ["banshee", "fargo", "house", "csi", "ncis"],
  method: 'get'
});

var update = function (){
    var selectionLength = $('form .ms-sel-item').length;
  $('.selection-name').text(selectionLength);
  console.log('Selection is ' + selectionLength);
}

$('form input').on('blur', function(){

 update();

});
$(window).on('keyup', function(e){
 if(e.keyCode === 13){

  update();
  $(this).blur();
 }

});
$(window).on('click', function(e){
  update();
  $(this).blur();
});

Let me know if there was any issue. I hope it helps.

alireza
  • 518
  • 5
  • 15
1
$(ms).on('blur', function(c,e){
    var selecteion = e.getSelection();
    if(selecteion[0]){ 
        console.log(selecteion[0]);
    }
});