0

我的页面有一个文本框。用户将在其中输入一个字符。该字符我必须与列表项值匹配,如果匹配发生,所有值都将被打印。假设用户输入“T”,那么所有以“开头的列表项” T”将被打印。

这是 HTML 代码。

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<input type="text" id="text1"  class="cal" />
<input type="button" value="calculate" id="Button2" />

这是 jQuery 代码。

$(document).ready(function() {
    $("#calculate").click(function() {
        var getsValue = $("#textbox1").val();
        $("ul > li").each(function() {
            if (getsValue == $(this).text()) {
                "print here"
            }
            else {
                alert("no")
            }
        });
    });
});

如果我输入整个字符串,它就可以工作,但我只需要输入一个字符。请帮忙。谢谢你。

4

4 回答 4

2
$(document).ready(function() {
    $("#textbox1").on("keyup", function() {
        var getsValue = $(this).val().toUpperCase();

        $("ul > li").each(function() {
            if (getsValue == $(this).text().charAt(0)) {
                document.write( $(this).text() );
            }
            else {
                alert("no")
            }
        });
    });
});​

演示

于 2012-08-27T10:54:05.007 回答
1

更改此行

  if (getsValue == $(this).text()) {
                "print here"
    }

作为

   if ($(this).text().indexOf(getsValue)==0) {
            "print here"
     }
于 2012-08-27T10:55:26.817 回答
1

这是您的更正代码..

$(document).ready(function() {

    $("#Button2").click(function() {
       var Arr=[];
        $('li').each(function(){Arr.push($(this).html());});
        var textValue=$('#text1').val();
        Arr=$.grep(Arr,function(n){return (n.substring(0,1))==textValue;});
        alert(Arr);
    });

});

工作演示

​</p>

于 2012-08-27T11:00:27.590 回答
0
$(document).ready(function () {

    $("#text1").keyup(function () {

         $("ul > li").each(function () {             
                if($("#text1").val() == $(this).text().charAt(0)) {
                    $("#text1").val($(this).text());
                }


         });
        });


});

您可以添加大写小写转换

于 2012-08-27T11:20:06.510 回答