views:

43

answers:

1

I'm using the Jquery Validation plugin to validate and submit my forms.

I want to be able to remove unnecessary form field values from the form data before they get posted to the server.

I figured that the submitHandler would be the best place for this - here is a sample of my code:

submitHandler: function(form) {
if (form.elements["billddress2"].value == "Suite/Apt"){
delete form.elements["billddress2"];    
}

if (form.elements["mobile"].value == "Mobile Number"){
delete form.elements["mobile"];
}

if (form.elements["questionid_46"].value == "Guest Email"){
delete form.elements["questionid_46"];
}

form.submit();
}

The problem is that the data still gets passed. I know that I have the right properties, since i tested them using form.elements["name"].value.

Anyone know why I can't delete HTMLFormElement Object properties?

A: 

The problem is that delete is meant to remove properties from objects, whereas you're trying to remove elements from the DOM. In your callback function, form is a DOM element, so you can't remove its children with delete. You could try using remove on the form elements (you'll have to turn them into jQuery objects with $ first), like this:

submitHandler: function(form) {
  var form = $(form);

  if (form.elements["billddress2"].value == "Suite/Apt"){
    $('input[name="billddress2"]', form).remove();
  }

  if (form.elements["mobile"].value == "Mobile Number"){
    $('input[name="mobile"]', form).remove();
  }

  if (form.elements["questionid_46"].value == "Guest Email"){
    $('input[name="questionid_46"]', form).remove();
  }

  form.submit();
}
No Surprises