How can I make a browser display all datalist options when a default value is set?

前端 未结 5 1691
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 17:01

I have an HTML form with a datalist and where the value is set with PHP, like

\">
 

        
5条回答
  •  离开以前
    2020-12-15 17:44

    The solutions above are great, but if the user naturally just clicks next to the placeholder value, inside the input box, intending to keep and continue it, it will become completely erased.

    So based on the solutions above, I did the following solution for me:

    HTML:

    
     
      
    

    JS:

    jQuery(document).ready(function ($) {
        function putValueBackFromPlaceholder() {
            var $this = $('#other');
            if ($this.val() === '') {
                $this.val($this.attr('placeholder'));
                $this.attr('placeholder','');
            }
        }
    
        $('#other')
            .on('click', function(e) {
                var $this = $(this);
                var inpLeft = $this.offset().left;
                var inpWidth = $this.width();
                var clickedLeft = e.clientX;
                var clickedInInpLeft = clickedLeft - inpLeft;
                var arrowBtnWidth = 12;
                if ((inpWidth - clickedInInpLeft) < arrowBtnWidth ) {
                    $this.attr('placeholder',$this.val());
                    $this.val('');
                }
                else {
                    putValueBackFromPlaceholder();
                }
            })
            .on('mouseleave', putValueBackFromPlaceholder);
    });
    

    For me there're many input boxes on the page, and I want only this one to have this behavior, so I work with id and have it "personal." If you wish to change it to the more generic function, you'll have to bind putValueBackFromPlaceholder with the element, on which the click happened, and the event itself.

提交回复
热议问题