Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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.

like image 727
nonezumi Avatar asked Nov 06 '11 18:11

nonezumi


People also ask

How do you stop an empty input react?

To disable a button when an input is empty with React, we can set the input's value as a state's value. Then we can use the state to conditionally disable the button when the state's value is empty. to create the name state with the useState hook.

How do you make input field empty after submit?

To clear an input field after submitting:Add a click event listener to a button. When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.


1 Answers

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.

like image 186
Ry- Avatar answered Sep 28 '22 21:09

Ry-