简体   繁体   中英

How to prevent submitting the HTML form's input field value if it empty

I have HTML form with input fields. Some of inputs can be empty, ie 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.

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.

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', '');
});

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);
      }
    });
  }
});

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.

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);

        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM