Saturday, July 17, 2010

Changing form actions with jQuery

I'm working on a simple cms in a side project. Naturally I have a page where administrators can create new web pages.

I'm using the jQuery version of TinyMCE for editing. It is worth a look if you need wysiwyg textarea editing.

I wanted to give my client the ability to preview the page before saving it. The solution was simple: change the form's action in the click handler.

The implementation eluded me for a while; although, it was completely obvious:
                $("#preview").click(function(event){
event.preventDefault();
$("#create_page_form").attr( "action", "/preview_page" );
$("#create_page_form").submit();
});

$("#submit").click(function(event){
event.preventDefault();
$("#create_page_form").attr( "action", "/create_page" );
$("#create_page_form").submit();
});


"#preview" and "#submit" are the ids of two links but could be buttons.

I thought I would post it in the event that anyone else Google's "jQuery change form action."

No comments: