简体   繁体   中英

Autocomplete Jquery remove everything after ' - '

I use a simply JQUERY Autocomplete to show possibles duplicates for certains records, like Name or address when user fill in a textfield.

Here code

<script type="text/javascript">
                $(function() {
                    var availableTags = <?php include('ajax/ajax_show.php'); ?>;
                    $("#name_value").autocomplete({
                        source: availableTags,
                        autoFocus:true
                    });
                });
            </script>

Below text filed are displayes results.

Name[____________________]
 Paul - 121.456.789-00
 Robert - 122.456.789-00
 Cid - 123.456.789-00

How to remove all after - (space hyphen space) and everything after it and have in textfield only name like Paul, Robert or Cid?

If you cannot change the ajax/ajax_show.php to give you the data the way you want, one of doing that is by using RegEx and replace everything after the - with javascript.

$(function() {
  var availableTags = <?php include('ajax/ajax_show.php'); ?>;
  $("#name_value").autocomplete({
    source: availableTags.map(function(v) { return v.replace(/(^[^-]*) .*/, '$1') }),
    autoFocus:true
   });
 });

Basically, this solution is using the map function to iterate over all elements and create a new array with the elements "cleaned" up. The method replace will use a regular expression (^[^-]*) .* to grab everything that's before the dash.

You can play with the regular expression if you want something more specific, another example that would work is: /^(.*) - .*$/

If possible, I think you'd be better off returning your data from ajax_show.php as json, like:

[
  {
   "value": "121.456.789-00",
   "label": "Paul"
  },
  {
   "value": "122.456.789-00",
   "label": "Robert"
  },
  ... 
]

Then, as shown in the jQuery UI docs here: https://jqueryui.com/autocomplete/#custom-data (under the 'Custom Data and display' tab), it will only use the name as the label but you'll still have access to the Id (the value property).

And as added good news, the way you pass your data in (by assigning it to the 'source' property) doesn't need to change at all.

To simply remove the numbers and show the name in an input box, you can use substr and indexOf (or you can work with regular expressions and replace if you prefer). Like this:

$( "#name_value" ).autocomplete({
    select: function( event, ui ) {
        $('#myInputBox').text(ui.item.value.substr(0, ui.item.value.indexOf(" - ")));
    }
});    

You might want to look up these two functions here and here to see how this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM