Mikey S.
Mikey S.

Reputation: 3331

Problem with focus event in chrome

I have the following script in my html page:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var k_InitialTextBoxValue = "Please enter a cd name";

        function requestSuggestion(partialCdName) {
            $.ajax({
                type: "GET",
                url: "Web1",
                data: "suggest=" + partialCdName,
                success: function (msg) {
                    alert(msg);
                }
            });
        }

        $("#textCdName").val(k_InitialTextBoxValue);

        $("#textCdName").focus(function () {
            alert($(this).val());
            /*if ($(this).val() == k_InitialTextBoxValue) {
                $(this).val() = "";
            }*/
        });


        $("#textCdName").keyup(function () {
            requestSuggestion($("#textCdName").val());
        });
    });
</script>

Everytime I focus the #textCdName text box element once, I got an infinite number of alert windows instead of one. This occurs in Chrome (v13), in IE it works fine.

Did this occure to anyone? how do I solve this issue?

Upvotes: 0

Views: 329

Answers (1)

Jamie Dixon
Jamie Dixon

Reputation: 53991

This makes sense because when you throw an alert, the textbox loses focus (focus is now on the alert dialog).

When you dismist the alert box, the textbox gets focus once more, resulting in a new focus event firing and thus a new alert.

Instead of using an alert to debug your code, consider using console.log which adds the message to the console (you'll need a console viewer to see the messages, I'm not sure if there's one built in to Chrome).

console.log($(this).val());

Upvotes: 1

Related Questions