Handling form data from javascript function
I have a form with an ID of 'manage_campaigns'.
I'm trying to call a function and send the form data to a javascript function by using this f开发者_JAVA技巧or the submit button, onclick:
javascript:updateAffiliateCampaigns(this);
This is the javascript function I have so far:
function updateAffiliateCampaigns(oForm) {}
I really only have a checkbox list of campaign id's that are being used in the form. How would I pass which items are checked to the function, and then how would I handle the data in the javascript function?
You might use jquery (http://jsfiddle.net/bkAMR/)
$('#manage_campaigns').submit(function(){
var formData = $(this).serialize();
$.ajax({
url: $(this).attr('action'),
data: formData,
success: function(data) {
// I got Donut
alert(data);
},
});
return false;
})
Ok, we've got a few things to cover before getting to your actual question
- The
javascript:
pseudo-protocol is only useful inhref
attributes of anchor elements - When using
this
inside an event attribute (likeonclick
) it always refers to the element itself. So if you put that on a submit button like so<input type="submit" onclick="updateAffiliateCampaigns(this)"
thenthis
will not reference the form, but the submit button itself - But that's OK because all form element DOM nodes have a
form
property that references their containing form node. - Submit buttons try to submit the form regardless of any javascript execution unless you use javascript to cancel the default action, which in this example is achieved by returning
false
to the event attribute
Now that we've covered that...
DOM form
objects have a property called elements
, which itself has properties representing the form element's names.
So with this as our example form
<form>
<input type="checkbox" name="campaign" value="1" />
<input type="checkbox" name="campaign" value="2" />
<input type="checkbox" name="campaign" value="3" />
<input type="submit" value="go" onclick="return updateAffiliateCampaigns( this.form );" />
</form>
You might then write your function like so
function updateAffiliateCampaigns( oForm )
{
console.log( );
var campaign = oForm.elements.campaign;
var checked = [];
for ( var i = 0, l = campaign.length; i < l; i++ )
{
if ( campaign[i].checked )
{
checked.push( campaign[i].value )
}
}
// The variable "checked" now contains the values of
// all checked items
return false;
}
Now is the part where I tell you that knowing this stuff is good, but you're also doing it The Hard Way. JavaScript libraries like jQuery and YUI have made doing tasks like this much, much simpler.
精彩评论