javascript - Dynamic loaded datalist options with AJAX in Firefox - Stack Overflow

For different reasons I want to get rid of Jquery UI autoplete function and replace it by HTML5 datalis

For different reasons I want to get rid of Jquery UI autoplete function and replace it by HTML5 datalists with dynamic loaded options field. I searched on this topic quite a few days and found also different answers on stackoverflow, like How do you refresh an HTML5 datalist using JavaScript? which I think is pretty close to what I search for.

I want the datalist for choosing tags, which will be written ma separated in the input field. The problem is that the datalist is only shown correctly for the first tag. The suggestion for the second one is not shown during typing "letters".

Now to the Process:

Typing: app

Server Response:

['apple','pinapple','snapper']

Shown datalist suggestion:

apple
pinapple
snapper

I now choose: apple, which is written to the input field, and afterwards:

Typing: ,in

Server Response:

['intest','instructor','insula']

Shown datalist suggestion: nothing, and this is the problem

BUT:

If I now hit backspace and delete the last sign, in the input field now stands:

apple, i

Then Firefox shows as options:

apple, intest
apple, instructor
apple, insula

I know that there is a parison with the value or innerHTML Field, so that I use:

<option value="apple, intest">apple, intest</option>

Now the code example:

HTML

<input list="autopleteList" type="text" class="form-control" name="Tags" id="Tags">
<datalist id="autopleteList"></datalist>

JS

// Used for querying only the last word of input field
function extractLast( term ) { return split( term ).pop(); }

$( document ).on( "input","*[name=Tags]", function( e ) {

    var _this  = $(this);
    var input  = _this.val();
    var first_part;

    // If a first tag is already inserted, now extract it for later use
    if ( input.split(/,|,\s*| /).length > 1 ) {
        var temp   = input.split(/,|,\s*| /);
        first_part = temp.filter(function (el) { return el.trim() != ""; }).slice(0,-1).join(', ') + ', ';
        console.log("EXTRACTED FIRST PART " + first_part);
    } else {
        first_part = '';    
    }

    if ( extractLast(input).length >= 2 ) {
        $.ajax({
        dataType: "json",
          type : 'POST',
          async:true,
          url: 'example/suggester',
            data: {term: extractLast( input )},
          success: function (data) {
                $("#autopleteList").empty();
                for (i=0; i<data.length; i++) {
                    $("#autopleteList").append('<option value="' + first_part + data[i] + '">' +  first_part + data[i] + '</option>');
                }                               

                // Array of Tags
                console.log("DATA FROM SERVER: " + data);

                // For inspection
               console.log("CONTENT OF AUTOCOMPLETE LIST: " + $('#autopleteList').html());
          }  
       });
    }
}); 

What I already have tested:

  1. Changing: from input to keypress, keyup, keydown, change -> no success
  2. Manually trigger events: _this.focus() or other --> no response
  3. Using JQuery show() on the datalist
  4. Embed the options into HTML-select. In this situation the datalist is also not working as expected, but the dropdown menu triggered by the select works fine and refreshes quickly.

So, finally:

How can I achieve, that the datalist options opens when typing letters without hitting backspace?

Thank you in advance!

For different reasons I want to get rid of Jquery UI autoplete function and replace it by HTML5 datalists with dynamic loaded options field. I searched on this topic quite a few days and found also different answers on stackoverflow, like How do you refresh an HTML5 datalist using JavaScript? which I think is pretty close to what I search for.

I want the datalist for choosing tags, which will be written ma separated in the input field. The problem is that the datalist is only shown correctly for the first tag. The suggestion for the second one is not shown during typing "letters".

Now to the Process:

Typing: app

Server Response:

['apple','pinapple','snapper']

Shown datalist suggestion:

apple
pinapple
snapper

I now choose: apple, which is written to the input field, and afterwards:

Typing: ,in

Server Response:

['intest','instructor','insula']

Shown datalist suggestion: nothing, and this is the problem

BUT:

If I now hit backspace and delete the last sign, in the input field now stands:

apple, i

Then Firefox shows as options:

apple, intest
apple, instructor
apple, insula

I know that there is a parison with the value or innerHTML Field, so that I use:

<option value="apple, intest">apple, intest</option>

Now the code example:

HTML

<input list="autopleteList" type="text" class="form-control" name="Tags" id="Tags">
<datalist id="autopleteList"></datalist>

JS

// Used for querying only the last word of input field
function extractLast( term ) { return split( term ).pop(); }

$( document ).on( "input","*[name=Tags]", function( e ) {

    var _this  = $(this);
    var input  = _this.val();
    var first_part;

    // If a first tag is already inserted, now extract it for later use
    if ( input.split(/,|,\s*| /).length > 1 ) {
        var temp   = input.split(/,|,\s*| /);
        first_part = temp.filter(function (el) { return el.trim() != ""; }).slice(0,-1).join(', ') + ', ';
        console.log("EXTRACTED FIRST PART " + first_part);
    } else {
        first_part = '';    
    }

    if ( extractLast(input).length >= 2 ) {
        $.ajax({
        dataType: "json",
          type : 'POST',
          async:true,
          url: 'example./suggester',
            data: {term: extractLast( input )},
          success: function (data) {
                $("#autopleteList").empty();
                for (i=0; i<data.length; i++) {
                    $("#autopleteList").append('<option value="' + first_part + data[i] + '">' +  first_part + data[i] + '</option>');
                }                               

                // Array of Tags
                console.log("DATA FROM SERVER: " + data);

                // For inspection
               console.log("CONTENT OF AUTOCOMPLETE LIST: " + $('#autopleteList').html());
          }  
       });
    }
}); 

What I already have tested:

  1. Changing: from input to keypress, keyup, keydown, change -> no success
  2. Manually trigger events: _this.focus() or other --> no response
  3. Using JQuery show() on the datalist
  4. Embed the options into HTML-select. In this situation the datalist is also not working as expected, but the dropdown menu triggered by the select works fine and refreshes quickly.

So, finally:

How can I achieve, that the datalist options opens when typing letters without hitting backspace?

Thank you in advance!

Share Improve this question edited Oct 31, 2018 at 22:25 marc_s 757k184 gold badges1.4k silver badges1.5k bronze badges asked Oct 26, 2018 at 15:54 mapaonsomapaonso 331 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

I stumbled upon this post which exactly describes the issue I was facing and was surprised to see no answers. The autoplete attribute needs to be set. In your case

<input autoComplete="off" list="autopleteList" type="text" class="form-control" name="Tags" id="Tags">

Note the capital C in the attribute.

According to this post, the problem was in React which uses camel-cased attributes. I'm not using React, but it worked for me nevertheless.

I also had the issue of having to populate an HTML Datalist with Ajax via jQuery, and the elements would not show up without hitting backspace on Firefox, despite working on Edge and Chrome. The workaround posted by Shrestha Ghosh did not work for me, neither did another workaround posted here, which suggested setting the autoplete="off" then immediately back to autoplete="on" with JavaScript/jQuery (i.e. with Element.SetAttribute() or jQuery.attr() respectively).

Instead, I noticed that the datalist would show up if I unfocused and refocused (i.e. clicked off then clicked in) the HTML input element. So, if anybody for which this issue is still relevant can use jQuery, it might be worth trying jQuery.Blur() and jQuery.Focus() too; this is a solution I haven't seen posted yet (tested on Firefox 80.0 64-bit).

That is:

$("#your-input-element").keypress(function(){
    $(this).blur();
    $(this).focus();
}

Note keypress instead of keydown; this avoids triggering the blur and focus when trying to navigate down the list with the down-arrow key. It's not a fantastically elegant solution, but for my use case it works quite well.

I had similar issue on Firefox where the drop down is not showing even if the result came back (JS HttpRequest) and I can see it at the DOM.

the solution for me was to add empty (as shown below) and replace it with the new data which came after sending the request.

<div class="form-group-input">
      <label for="client_name" class="hidden-label">Client Name</label>
      <input list="clients_list" autoComplete="off" type="text" name="client_name" id="client_name" placeholder="Client Name" >
      <datalist id="clients_list"><option value=""></datalist>
</div><!-- form group input -->

Thanks

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744998972a4605374.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信