Focus Input Box On Load

后端 未结 11 2567
无人及你
无人及你 2020-11-30 01:10

How can the cursor be focus on a specific input box on page load?

Is it posible to retain initial text value as well and place cursor at end of input?



        
11条回答
  •  渐次进展
    2020-11-30 01:34

    There are two parts to your question.

    1) How to focus an input on page load?

    You can just add the autofocus attribute to the input.

    
    

    However, this might not be supported in all browsers, so we can use javascript.

    window.onload = function() {
      var input = document.getElementById("myinputbox").focus();
    }
    

    2) How to place cursor at the end of the input text?

    Here's a non-jQuery solution with some borrowed code from another SO answer.

    function placeCursorAtEnd() {
      if (this.setSelectionRange) {
        // Double the length because Opera is inconsistent about 
        // whether a carriage return is one character or two.
        var len = this.value.length * 2;
        this.setSelectionRange(len, len);
      } else {
        // This might work for browsers without setSelectionRange support.
        this.value = this.value;
      }
    
      if (this.nodeName === "TEXTAREA") {
        // This will scroll a textarea to the bottom if needed
        this.scrollTop = 999999;
      }
    };
    
    window.onload = function() {
      var input = document.getElementById("myinputbox");
    
      if (obj.addEventListener) {
        obj.addEventListener("focus", placeCursorAtEnd, false);
      } else if (obj.attachEvent) {
        obj.attachEvent('onfocus', placeCursorAtEnd);
      }
    
      input.focus();
    }
    

    Here's an example of how I would accomplish this with jQuery.

    
    
    
    

提交回复
热议问题