51

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.

Community
  • 1
  • 1
nonezumi
  • 653
  • 1
  • 5
  • 7
  • 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 Nov 20 '13 at 13:16
  • 1
    Actually, using `$('#commentary').attr('name', null)` seems to work in all browsers. – Siggen Nov 20 '13 at 13:25
  • `$('#commentary').removeAttr('name')` also works in all browsers – Lefunque Jun 16 '16 at 19:57

5 Answers5

46

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.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 6
    Now, in 2012, you may also use HTML5 `required`-attributes for modern browsers and use that JS as conditional fallback. – feeela Dec 01 '12 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 Jan 20 '15 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 Jan 21 '15 at 08: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 Jan 12 '16 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- Jan 12 '16 at 22:35
  • @Ryan and what if you want to specify the type of input? Ex: `checkbox`, `date`, `text` etc... – Safirah Jan 31 '17 at 22:20
  • @Safirah: Check whether it’s empty using something appropriate to its type (for checkbox, the `checked` property) and remove its name as shown here. – Ry- Feb 01 '17 at 01:46
  • IF I use the GET method to pass values into a search results page, it seems to not work as intended. all parameter names are passed empty ex. **SearchResults.php?name1=&name2=&name3=**, there is a workaround for that too? (for SELECT option **selected disabled** works like a charm, but for **input type="text"** or **input type="search"** that is not working. How do I prevent empty field values to be passed for this? – Szabolcs Horvath Feb 27 '23 at 13:10
13

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);
      }
    });
  }
});
Francesco Frassinelli
  • 3,145
  • 2
  • 31
  • 43
  • 1
    It seems that Internet Explorer doesn't support `formData.entries` and `formData.delete`. https://developer.mozilla.org/en-US/docs/Web/API/FormData#browser_compatibility – Erik Joling Feb 17 '21 at 16:53
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', '');
});
fduch
  • 61
  • 1
  • 1
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.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
  • 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 Nov 06 '11 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. – Remy Lebeau Nov 06 '11 at 19:49
  • Yes, that is my wonder too. Unfortunately, I can not change backend, even its behavior is not common. – nonezumi Nov 06 '11 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. – josh.chavanne Jan 01 '15 at 06:49
  • 1
    @josh.chavanne Using a submit input versus a button didn't make any difference in my testing. – Apollo Data Sep 13 '16 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);

        }
    });
});
ASH
  • 980
  • 1
  • 9
  • 22
  • Be careful of concatenating strings like that. It's better to use [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent). – John Coker Oct 13 '20 at 17:48