views:

45

answers:

4

I have a form submit link labeled "OK", and I want to have a spinner to indicate that something is happening when it's clicked. I tried adding an image to the clicked span before submitting the form, but it doesn't appear:

function submitMyForm() {
    $(this).html($(this).html() + "&nbsp;&nbsp;<img src='/img/spinner.gif'>");
    $("#my_form").submit();
}

with HTML:

<em class="ok_btn">
    <a href="javascript:void(0);" onclick="submitMyForm();">OK</a>
</em>

It seems like the form submit happens before the page is re-painted. Is there way to get the page to re-paint, and then submit the form?

A: 

Try changing this line:

$(this).html($(this).html() + "&nbsp;&nbsp;<img src='/img/spinner.gif'>");

To:

$('body').append("&nbsp;&nbsp;<img src='/img/spinner.gif'>");

I haven't tested that, but I think it should work.

Colin O'Dell
+3  A: 

Submitting a form stops ALL other execution. So what's likely happening is your HTML doesn't have time to get updated before your submit action occurs. Try adding a delay:

function submitMyForm() {
    $(this).html($(this).html() + "&nbsp;&nbsp;<img src='/img/spinner.gif'>");
   window.setTimeout(function(){ $("#my_form").submit()},500)
}
Diodeus
+1  A: 

$(this) won't refer to anything because nothing has been passed. I think you need to pass the element to the function with:

<a href="javascript:void(0);" onclick="submitMyForm(this);">OK</a>

then the js would become:

function submitMyForm(el) {
    $(el).html($(el).html() + "  ");
Alex
This was the crux of the matter. Adding a delay as Diodeus and @Mike Webb suggest is also a good idea.
Ned Batchelder
A: 

I would suggest, as I mentioned in my comment, that you probably want to add the image to a div. Something like this:

... your html code here ...
<div id="spinnerDiv">
</div>

Then add a timeout to the form like this:

function submitMyForm() {
    $("#spinnerDiv").html("<img src='/img/spinner.gif'>");
    window.setTimeout(function()
    {
        $("#my_form").submit();
    }, 500);
}
Mike Webb