Separating array elements

I have an array like this:

var arr = ["1,JOAQUIN", "2,BERNARDINO", "3,MODOC", "4,MADERA"];

I would like to break it individually, for example

1 JOAQUIN
2 BERNARDINO
3 MODOC 
4 MADERA

I am trying to do the following:

1. show the numbers (first index) in the jQuery UI
2. autocomplete list and their corresponding name in another text box.

Here is my code

var arr = ["1,JOAQUIN", "2,BERNARDINO", "3,MODOC", "4,MADERA"];
$('input').autocomplete({
    source: json,
    select: function(event, ui) { 
        var str = ui.item.value.split(',');
        var lastIndex = str.length -1;
        $('#two').val(str[lastIndex]);     //ACHEIVED 2nd   
    }
});

However, I have a second point and am trying to find a solution to my first question.

Here is the JSFiddle

Share your suggestions and point me in the right direction.

+4
source share
2 answers

According to the autocomplete documentation, you can set an array of objects as a property source.

label . value , . , , , value, value label.

$('input').autocomplete({
    source: arr.map(function(elem) {
              return { 
                 'label': elem.split(',')[0], 
                 'value': elem.split(',')[1] 
              }
    }),
    select: function(event, ui) { 
        $('#two').val(ui.item.value);    
        return false;
    }
});

http://jsfiddle.net/ETwtF/

, IE Array object .map(), ES5, jQuery $.map():

$.map(arr, function(_, elem) {
     return { 
         'label': elem.split(',')[0], 
         'value': elem.split(',')[1] 
     }
});
+4

return false;

Fiddle

<input type='text' id="one" />
<input type='text' id="two" />  

var json = ["1,JOAQUIN", "2,BERNARDINO", "3,MODOC", "4,MADERA"];
$('input').autocomplete({
  source: json,
  select: function(event, ui) { 
      var str = ui.item.value.split(',');
      var lastIndex = str.length -1;
      $('#one').val(str[0]);
      $('#two').val(str[lastIndex]);     //ACHEIVED 2nd   
      return false;
  }
});
+1

Source: https://habr.com/ru/post/1502552/


All Articles