在文本框中找到输入的第一个字符 [英] Find the first character of input in a textbox

查看:147
本文介绍了在文本框中找到输入的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在实现以下方面:

I am stuck in implementing the following:

  1. 用户开始在文本框中输入内容.
  2. 页面上的javascript捕获第一个键入的字符,确认它是英文字母(a-z,A-Z)并将其转换为小写字母(如有必要).
  3. 根据输入进行XMLHttp请求(即,如果第一个输入字符为a,则获取a.xml,如果b为b.xml,依此类推).

我知道如何做最后一部分(发出xmlhttp请求),但是在如何捕获第一个字符并对其进行验证(以在所有浏览器上都可以使用的方式)上有些固执.请指导.谢谢.

I know how to do the last part (make the xmlhttp request) but am kind of stuck on how to capture the first character and validate it (in a way that works on all browsers). Please guide. Thanks.

说明:这是在不需要服务器端程序的情况下创建类似于自动完成下拉菜单的Google建议.

Clarification: This is to create a Google Suggest like autocomplete-drop-down menu without the need for server side programs.

推荐答案

类似的方法应该起作用:

Something like this should work:

HTML:

<input type="text" id="myField" />

在JS中:

window.onload = function() {
    document.getElementById('myField').onkeyup = function() {
        // Validate that the first letter is A-Za-z and capture it
        var letter = this.value.match(/^([A-Za-z])/);

        // If a letter was found
        if(letter !== null) {
            // Change it to lowercase and update the value
            letter = letter[0].toLowerCase();
            this.value = letter + this.value.substring(1);

            // Do the request
        }
    }
}

我的vanilla-JS技能有些生锈,但这应该可以解决问题.只是为了简单起见,这与使用jQuery相同:

My vanilla-JS skills are a bit rusty but this should do the trick. Just for the heck of it, here's the same using jQuery:

$(function() {
    $('#myField').keyup(function() {
        var letter = $(this).val().match(/^([A-Za-z])/);

        // If a letter was found
        if(letter !== null) {
            // Change it to lowercase and update the value
            letter = letter[0].toLowerCase();
            $(this).val(letter + $(this).val().substring(1);

            // Do the request
        }
    });
});

这篇关于在文本框中找到输入的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆