How can I add an unremovable prefix to an HTML input field?

前端 未结 16 1426
猫巷女王i
猫巷女王i 2020-12-13 04:23

Using jQuery, how can I add a default value of http:// into an input field that can’t be removed, but that still allows you to type a URL after it?

Defa

16条回答
  •  猫巷女王i
    2020-12-13 05:04

    All tested!

    $('#myUrl').keyup(function(e) {
      if (this.value.length < 7) {
        this.value = 'http://';
      } else if (this.value.indexOf('http://') !== 0) {
        this.value = 'http://' + String.fromCharCode(e.which);
      }
    });
    
    
    

提交回复
热议问题