0

I am trying to implement an textbox component. It should allow user to fill the input with autofill menu when it is blank; and disable the autofill if there are any texts in the input, and dismiss the autofill menu if it is displayed at the same time.

I've tried to set the autocomplete attribute of the input when the change event is fired. The value can be flipped correctly, but turning the value off does not dismiss the autofill menu. Wondering if there are any javascript solutions to do it.

html:

<input id=​"addrBox" name=​"addrBox" autocomplete=​"off" class placeholder=​"Start typing your address to get auto-suggestions…">

js:

$('#addrBox').on('click focus change keydown', function(){
    var val = $('#addrBox').val(); 
    if(val.length){
        $('#addrBox').attr('autocomplete', 'off')
    }
    else{
        $('#addrBox').attr('autocomplete', 'on')
    }
})

Screen shot:
I click the empty input box, it shows the autofill menu, which is expected. Then I continue to enter 1, the autocomplete attribute is turned off, however the menu is still there.

enter image description here

shaosh
  • 618
  • 2
  • 7
  • 26

1 Answers1

1

Figured out how to dismiss the autofill the menu. It can be done by setting autocomplete to new-password, instead of off.

$('#addrBox').on('mouseup keyup', function(){
    var val = $('#addrBox').val(); 
    val = val.length;
    if(val === 0){
        $('#addrBox').attr('autocomplete', 'on');
    }
    else{
        $('#addrBox').attr('autocomplete', 'new-password');
    }
}).on('mousedown keydown', function(){
    var val = $('#addrBox').val(); 
    var length = val.length;
    if(!length){
        $('#addrBox').attr('autocomplete', 'new-password');
    }    
})

The reference is https://stackoverflow.com/a/36584903/2177408

Community
  • 1
  • 1
shaosh
  • 618
  • 2
  • 7
  • 26