I have the following HTML:
<input class="button" name="save" onclick="$(this).replaceWith('<img src=http://www.example.com/images/ajax-loader.gif />');" type="submit" value="SUBMIT">
When clicking on the button, the form no longer attempts to submit, but replaces itself with a turning AJAX loading gif and does nothing. If I remove the onclick portion, it submits.
Long story, this is for a client, but I can’t give them the same thing in the form of
$(function() { $(input[name=save]).on({click:function() { $(this).replaceWith(...); } }); });
Why won’t this still submit after replacing itself? I’m not e.preventDefault()‘ing anywhere.
According to the replaceWith() documentation:
When an element is removed, as per remove() documentation:
I’m assuming that is why the submit is not executing.
If you want the form to still submit you can manually trigger the submit after you have replaced the element.
DEMO – Submitting the form while replacing the button element
For readability, to demonstrate, I have moved the binding of the click event into script rather than in-line of the element. I also added an id in case of multiple forms, which is not really needed if you only got a single form as you can simply bind to
$("form").on("submit")instead thenEdit – Same code using in-line
onclickMoving the code into the in-line
onClickstill works.Regarding the form submission,
$(this)will be the button before it is replaced and be gone after, hence$(this).closest("form").submit()or any other form of selector using$(this)won’t work.You must target your form for submit neutrally without using
$(this)by either using$("form").submit()or if you have mutiple forms use an id as in$("#myForm").submit().DEMO – Submitting a form manually after replacing the button using inline onclick
As a side note, if you want the image to be displayed before the submit event is triggered you can apply a little trick like this:
You can apply the same off course in your in-line onClick.