[tech] submitting forms with javascript
I keep running into these stupid small issues with javascript and prototype. Sometimes they seem so simple, so easy, but somehow you can’t figure them out. This next thing should have been logical, I should have known.. and still, I spent 20 minutes figuring out why it didn’t work.
The goal: a mass action button. On the php side, I use the name of the button to process the form. On the html side, I have a form with a bunch of radio buttons and one submit button. On the javascript side, a simple confirm function.
Here’s the code for the button:
I simple want that onclick to do a confirm, if you press yes, go ahead and submit form, otherwise, stay where you are. The confirm code uses a prototype window plugin. The javascript function, returns true if you press yes, and it does a form.submit(). Like so:
input name="DeleteItems" id="DeleteItems" type="submit" value="Delete Item(s)" onclick="fncConfirmForm()"
function fncConfirmForm() {
Dialog.confirm("Are you sure you want to delete these items?", {
windowParameters : {width:200},
okLabel : "Delete",
cancelLabel : "Cancel",
onOk : function(){ $('ItemsFormName').submit(); return true; },
onCancel: function(){return false;}
});
}
But that didn’t work.
First, the button I used kept submitting as soon as I pressed it. It didnt even wait for me to click Yes/Delete. So I changed the button type to “button” instead of “submit”. That stopped the form from submitting.
But it still didn’t work.
Turns out when you make it a type button, that input element doesn’t actually get submitted with the form. So the page was submitting after I pressed Yes/Delete, but it wasn’t going in the php part.
I had to add a hidden field with the name I needed, and make the button that has the onclick a fake button. Like this:
input name="DeleteItems" id="DeleteItems" type="hidden" value="true"
input name=”DeleteItemsFake” id=”DeleteItemsFake” type=”button” value=”true” onclick=”fncConfirmForm()”
Should have been simple huh?
PS: I cannot figure out how to show code here without tumblr going bonkers… anyone have any ideas?