1

Possible Duplicate:
How do I use jQuery's form.serialize but exclude empty fields

I need to remove the unused input names from a Serialize string if they're not filled in on a form. See the attached JSFIddle. Currently if someone only fills in Q1 & Q3 the names the string appears as follows /static/url/to/file.php?Q1=Bob&Q2=&Q3=Dan&Q4=. I'd therefore like to get rid of the Q2= and Q4= names from the string before submission. Thanks

JSFiddle - Serialize

2

1 Answer 1

1

try this:

$('#form1').find('input[type="text"]').not('#url').change(function(){
    var val = "";
    var url = '/static/url/to/file.php?';
    $('form input[type="text"]').not('#url').each(function(){
        if ($.trim(this.value).length > 0 ) { 
          val += ($(this).attr('name') + "=" + this.value + "&");
        }  
    })
    $('#url').val(url+val);
});

$('#button').click(function(){
    window.location = $('#url').val();
});

DEMO

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks...I just need the input answers to attach themselves to the URL in the visible result box? The results box is hidden behind a submit button. Sorry I'm a bit of a jquery novice.
Great stuff..many thanks. One problem, the Demo seems to be including the url twice in the results box?
@SamuelTattersfield you are welcome. not for me on firefox.
Strange...I'm on Firefox also, I also tried it in chrome and the string looked like so /static/url/to/file.php?Q1=bob&Q3=dan&Q4=rob&url=/static/url/to/file.php?Q1=bob&Q3=dan&url=/static/url/to/file.php?Q1=bob&&&
Still giving the same results?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.