0

I have an input field. When the user start typing I'm using the "click" function to do some logic with the text.

The thing I would like to do is to have a list that gets updated when the user have entered more than 3 characters.

As soon as the users enters more characters the "Dona" part below gets updated.

The user enteres "Dona.."

The list says:

Add "Dona" as a contact Add a task with the Subject "Dona" and so on

What I have today is:

$("#inp").keyup(function() {
if ($("#inp").text.length > 3) {
 $("#list").append('<li></li>')
}
});

I cant get the counter to work. I'm able to append

  • but dont know how to pick it again later for updating

  • 4

    2 回答 2

    0

    text is a method, text(). But since you're dealing with a field, you should be using val() instead.

    Change your code to

    $("#inp").on('keyup', function() {
        if ($(this).val().length > 3) { //<-- text(), not text
            $("#list").append('<li>'+$(this).val()+'</li>')
        }
    });
    

    Also, note I use $(this) (no need to make jQuery look up the element again) and have switched to using on() to bind the event.

    JSFiddle demo

    于 2012-07-15T09:39:04.770 回答
    0

    I tried the code you suggested. My code looks like this now

    Nothing happens when I enter more than 3 characters.

    <script type="text/javascript" src="http://localhost:53230/Scripts/jquery-1.7.2.js">          </script>
    <h1>test</h1>
    <input id="inp" type="text" class="t" />
    
    <ul id="list">
    </ul>
    
    <script type="text/javascript">
    $("#inp").click(function () {
        //SOME OTHER NOT RELEVANT CODE
    });
    
    $("#inp").on('keyup', function () {
            if ($(this).text().length > 3) { 
                $("#list").append('<li></li>')
            }
        });
       </script>
    
    于 2012-07-15T11:46:26.483 回答