views:

330

answers:

2

I am doing a small jQuery function. What this function should do is on leaving textbox it should display text from textbox as alert, clears textbox and again set focus in the same textbox. It is doing two of three tasks showing text in alert and clearing textbox but it is not setting focus back in that textbox.

Please note this textbox is in a form and I have used tab index here as well. When I clicked ok in alert it move focus to the next textbox having next tab index.

Here is my code:

<script type="text/javascript">

    function pageLoad() {
        $("input[id$='txtEmailAddress']").blur(CheckOnServer);
    }

    function CheckOnServer() {
        alert($("input[id$='txtEmailAddress']").val());
        $("input[id$='txtEmailAddress']").val("");
        $("input[id$='txtEmailAddress']").focus();
        alert("2");
    }
</script>
+1  A: 

Attaching the CheckOnServer function to the blur event of your input field seems really weird to me. I haven't tested your code, so I might be wrong, but as I see it, this is saying:

When input[id$='txtEmailAddress'] loses focus, do some stuff, and give it focus again. This is gonna be a never ending loop...

As to why the wrong field is gaining focus, I have no better idea than Ben.

Adrian Schmidt
+1  A: 

If there's more than one field ending with 'txtEmailAddress', wouldn't your code be trying to assign focus to each of them at the same time? I'm thinking that the wrong field is gaining focus because $(input[id$='txtEmailAddress'] isn't a single DOM element, and jQuery isn't designed to run the focus function on an array of objects.

I agree with Adrian, though. If you get it to work the way that you want, you will never be able to leave that field. If you want it to do the 'alert, clear, refocus' dance just one time, remember to clear the onblur function afterwards.

monksp