Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete empty values from form's params before submitting it

I have some javascript which catches changes to a form then calls the form's regular submit function. The form is a GET form (for a search) and i have lots of empty attributes come through in the params. What i'd like to do is to delete any empty attributes before submitting, to get a cleaner url: for example, if someone changes the 'subject' select to 'english' i want their search url to be

http://localhost:3000/quizzes?subject=English

rather than

http://localhost:3000/quizzes?term=&subject=English&topic=&age_group_id=&difficulty_id=&made_by=&order=&style=

as it is at the moment. This is just purely for the purpose of having a cleaner and more meaningful url to link to and for people's bookmarks etc. So, what i need is something along these lines, but this isn't right as i'm not editing the actual form but a js object made from the form's params:

  quizSearchForm = jQuery("#searchForm");
  formParams = quizSearchForm.serializeArray();
  //remove any empty fields from the form params before submitting, for a cleaner url
  //this won't work as we're not changing the form, just an object made from it.
  for (i in formParams) {
    if (formParams[i] === null || formParams[i] === "") {
      delete formParams[i];
    }
  }
  //submit the form

I think i'm close with this, but i'm missing the step of how to edit the actual form's attributes rather than make another object and edit that.

grateful for any advice - max

EDIT - SOLVED - thanks to the many people who posted about this. Here's what i have, which seems to work perfectly.

function submitSearchForm(){
  quizSearchForm = jQuery("#searchForm");
  //disable empty fields so they don't clutter up the url
  quizSearchForm.find(':input[value=""]').attr('disabled', true);
  quizSearchForm.submit();
}
like image 636
Max Williams Avatar asked Mar 10 '10 15:03

Max Williams


2 Answers

The inputs with attribute disabled set to true won't be submitted with the form. So in one jQuery line:

$(':input[value=""]').attr('disabled', true);
like image 83
rogeriopvl Avatar answered Nov 09 '22 09:11

rogeriopvl


$('form#searchForm').submit(function() {
    $(':input', this).each(function() {
        this.disabled = !($(this).val());
    });
});
like image 21
Marko Dumic Avatar answered Nov 09 '22 09:11

Marko Dumic