55

I have HTML form with input fields. Some of inputs can be empty, i.e. the value is "".

<input name="commentary" value="">

Just now, when commentary field is not set, it appears in submit url like: &commentary=

How I can remove empty inputs from the submit url, so when the commentary input is empty it would not be passed at all.

Thank you very much.

Update

Thanks to minitech answer, I could resolve it. JavaScript code is below:

$('#my-form-id').submit(function() {
  var commentary = $('#commentary').val(); 
  if (commentary === undefined || commentary === "") {
    $('#commentary').attr('name', 'empty_commentary');
  } else {
    $('#commentary').attr('name', 'commentary');        
  }
});

The only reason I have prefixed field name with "empty_" is that IE passes empty name in URL anyway.

3
  • 1
    Adding a 'disabled' attribute ($('#commentary').attr('disabled', 'disabled') is a possible workaround so IE8 doesn't pass empty name in the URL. There is a side-effect though : all empty fields will briefly turn gray before the form is submitted.
    – Siggen
    Commented Nov 20, 2013 at 13:16
  • 1
    Actually, using $('#commentary').attr('name', null) seems to work in all browsers.
    – Siggen
    Commented Nov 20, 2013 at 13:25
  • $('#commentary').removeAttr('name') also works in all browsers
    – Lefunque
    Commented Jun 16, 2016 at 19:57

5 Answers 5

47

This can only be done through JavaScript, as far as I know, so if you rely on this functionality you need to restructure. The idea, anyway, is to remove the name attribute from inputs you don’t want included:

jQuery:

$('#my-form-id').submit(function () {
    $(this)
        .find('input[name]')
        .filter(function () {
            return !this.value;
        })
        .prop('name', '');
});

No jQuery:

var myForm = document.getElementById('my-form-id');

myForm.addEventListener('submit', function () {
    var allInputs = myForm.getElementsByTagName('input');

    for (var i = 0; i < allInputs.length; i++) {
        var input = allInputs[i];

        if (input.name && !input.value) {
            input.name = '';
        }
    }
});

You might also want to reset the form afterwards, if you use a listener and cancel.

8
  • 6
    Now, in 2012, you may also use HTML5 required-attributes for modern browsers and use that JS as conditional fallback.
    – feeela
    Commented Dec 1, 2012 at 20:33
  • Works great for inputs but not select fields. What is the syntax for select fields as select[value=''] doesn't work?
    – ProNotion
    Commented Jan 20, 2015 at 17:44
  • To answer my own question. I finally managed to achieve what I needed using the following selector: $('select option[value=""]:selected').closest("select").attr('name', '');
    – ProNotion
    Commented Jan 21, 2015 at 8:56
  • I don't know, at least on latest Chrome version it still navigates, despite that js. This one worked for me: $('#searchForm').submit(function (evt) { if(!$('#searchInput').val()) evt.preventDefault(); });
    – Illidan
    Commented Jan 12, 2016 at 20:40
  • @Illidan: The point of this answer was to not cancel the navigation =) It looks like you just want regular validation. This question is about a very unusual case.
    – Ry-
    Commented Jan 12, 2016 at 22:35
17

I prefer not to alter the input elements (changing their names, or flagging them as disabled and so), because if you go back you could get a broken form.

Here is my solution instead, which relies on FormData:

window.addEventListener('load', function() {
  let forms = document.getElementsByClassName('skipEmptyFields');
  for (let form of forms) {
    form.addEventListener('formdata', function(event) {
      let formData = event.formData;
      for (let [name, value] of Array.from(formData.entries())) {
        if (value === '') formData.delete(name);
      }
    });
  }
});
2
  • 1
    It seems that Internet Explorer doesn't support formData.entries and formData.delete. developer.mozilla.org/en-US/docs/Web/API/… Commented Feb 17, 2021 at 16:53
  • This answer is not quite correct in the sense that FormData may have multiple values associated with a given key. As such you should fetch all of the values associated with a key using getAll, remove all of the existing values and then re-add the non-empty ones. Commented Dec 1, 2023 at 15:02
6

You probably don't want to match radio buttons. And if the form contains select's, you'll need to match them too.

With jQuery, you might use something like this:

$('#form-id').submit(function() {
    $(this).find('input[type!="radio"][value=""],select:not(:has(option:selected[value!=""]))').attr('name', '');
});
1
  • Nice one-liner!
    – rkok
    Commented May 20, 2019 at 6:57
5

Instead of using a submit-type input, use a button-type input for form submission. The JavaScript handler for the button-type input should call form's submit() method after checking that commentary is non-empty. You should also alert the user to their mistake (better with a red text on the page rather than the pop-up produced by alert()).

Remember that you should not rely solely on client-side input validation, though since it is always possible to send the form from a modified page or directly in HTTP.

5
  • Thank you. Just empty commentary completely valid. Just server backend does not accept it in form of "&commentary=". It requires that such empty parameter should not exist at all in post request.
    – nonezumi
    Commented Nov 6, 2011 at 19:12
  • Why does the backend require that? If the commentary is allowed to be blank, the backend needs to accept blank values being submitted. Commented Nov 6, 2011 at 19:49
  • Yes, that is my wonder too. Unfortunately, I can not change backend, even its behavior is not common.
    – nonezumi
    Commented Nov 6, 2011 at 20:08
  • This answer is the only mention of the differences in the way Submit and Button work differently. All named text fields with blank values do not submit by default any longer. Commented Jan 1, 2015 at 6:49
  • 1
    @josh.chavanne Using a submit input versus a button didn't make any difference in my testing. Commented Sep 13, 2016 at 20:12
0

Thankyou @Ryan

This is my full solution for this. I use Jersey and @BeanParam and this fixes the problem of "" & null inputs

$('#submitForm').click(function() {
    var url = "webapi/?";       
    var myForm = document.getElementById('myFormId');
    var allInputs = myForm.getElementsByTagName('input');

    for (var i = 0; i < allInputs.length; i++) {
        var input = allInputs[i];
        if (input.value != "" && input.name != "submitForm") {              
            url += input.name +'='+input.value+'&';
        }

    }
    console.log(url);

    $.ajax({
        method : "GET",
        url : url,

        data : {
        // data : "json",
        // method: "GET"
        },
        success : function(data) {
            console.log("Responce body from Server: \n" + JSON.stringify(data));
            $("#responce").html("");
            $("#responce").html(JSON.stringify(data));
        },
        error : function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus);

            console.log('Error: ' + errorThrown);

        }
    });
});
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.