1

I am submitting a large form. It has many fields with unspecified values, which translate to field=&field2=&field3....

I don't want these in the GET url. Only keep fields with non-empty value.

I figured out a way to do it with jquery:

$('#form').live('submit', function() {
    $('input[value=""]', '#form').remove();
});

which I thought would do exactly what I wanted.

But apparently I am missing something, because this selects and removes inputs with entered text as well, not just the empty ones.

The above selector (before remove()) contains <input type=​"text" class=​"input-medium" name=​"field1" id=​"field1" value>​, so it looks as if there is no value set. There is a value set though, as confirmed by $('input[name="field1"]').val(), which correctly returns the text that is also visible on screen.

What's up with that? Any ideas?


Using jquery 1.7.2, Chrome 18.0.1025.168.

0

3 Answers 3

3

Please use filtering of fields, since [value=""] selector checks the default states of the inputs.

$('#form').on('submit', function() {
    $(':input', this).filter(function() {
        return this.value.length == 0;
    }).remove();
});​

DEMO: http://jsfiddle.net/bCskH/

UPDATE: In order not removing input fields you can simply disable them:

$('#form').on('submit', function() {
    $(':input', this).filter(function() {
        return this.value.length == 0;
    }).prop('disabled', true);
});​

The effect will be the same, however IMHO much nicer :)

DEMO: http://jsfiddle.net/bCskH/1/

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

1 Comment

the prop() effect is indeed better than remove(), thanks!
2

You can use jquery selector and serialize() to select only input that has value here is the example

<form id="test">
    <input name="field1" value="Test"><br/>
    <input name="field2" value=""><br/>
    <input name="field3" value="value"><br/>
    <input id="btn" type="button" value="submit"/>
</form>​


$('#btn').on('click',function() {
    alert($('#test input[value != ""]').serialize());
});​

also I doubt, .live() will work in jquery 1.7 use .on() instead. See this link and it says it has been deprecated

Comments

1

[value=".."] accesses the attribute which is not synced with the current value. Besides that, you cannot specify a selector as context - so move #form into the main selector and use .filter() to restrict the matched elements to empty ones:

$('#form input').filter(function() {
    return !$(this).val();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.