Background: I need to append certain data to post; similar to what jQuery's ajaxSetup does that for asynchronous requests except I need it for native form submits.
I need to be able to add a couple of form fields to a form before it is submitted, but I want to make sure I don't add duplicate fields in case they're already there (i.e. original submit failed because of validation or something).
At first I thought something like this would be nice and coherent:
$("form").live("submit", function ()
{
var $this = $(this);
($this.find('#stuff') ||
$this.append('<input type="hidden" id="stuff" name="stuff" />'))
.val('some value');
// carry on with the native submit
// this is actually correct, as opposed to $this.submit()
// which would create a loop
this.submit();
});
Meaning look for #stuff, if it's not found create it, then set its value to "some value". However because the result of the .find() is actually a jQuery wrapper, it would be implicitly converted to a true meaning that even if there are no matching elements found, the .append() code would never be executed.
Is there a nice way to tackle this whole "look for an element and create it if it doesn't already exist" scenario?