2

I have a form like this

<form action="index.php" method="get">
  <input type="hidden" name="id" value="1">
  <input type="hidden" name="order_by" value="">
  <button type="submit">Submit</button>
</form>

It has some jQuery handlers to fill in "order_by" field. If I submit this form with empty "order_by" filed, I get an address like this: index.php?id=1&order_by=

What is the best way I can do to get following address after form submission if the "order_by" is empty: index.php?id=1 ?

4
  • What are you using exactly for form submission? Commented Sep 11, 2014 at 14:51
  • On submit, check if it's empty and, if it is, remove it from the DOM. Commented Sep 11, 2014 at 14:51
  • I don't use JavaScript for submission, just clean html form behaviour. Commented Sep 11, 2014 at 15:01
  • Does this answer your question? How to prevent submitting the HTML form's input field value if it empty Commented Sep 23, 2020 at 13:43

3 Answers 3

10

you can disable empty fields so they don't get added as data

$('form').submit(function(e){
    var emptyinputs = $(this).find('input').filter(function(){
        return !$.trim(this.value).length;  // get all empty fields
    }).prop('disabled',true);    
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is the only answer so far that truly answers the OP's question, which was how to not set the empty values in the first place. I had the same problem, where I didn't want the URL to get polluted with optional fields from a search form. This worked like a charm!
1

in php you can do like this

if(!isset($_GET['order_by']) || !$_GET['order_by'])
    return 'error msg';

or

if(empty($_GET['order_by']))
    return 'error msg';

change html like this

   <form action="index.php" method="get" onsubmit="return valid()">
  <input type="hidden" name="id" value="1">
  <input type="hidden" name="order_by" id="order_by" value="">
  <button type="submit">Submit</button>
  </form>

javascript:

  function valid(){
   if(!$('#order_by').val()){
       alert("Order by not found");
       return false;
    }
   return true;
 }

1 Comment

I need to avoid initialization of $_GET['order_by'] if it's empty in form, not it's validation at php level.
0
$('form#formID').submit(function(e){
     var emptyinputs = $(this).find('select').filter(function(){
     return !$.trim(this.value).length;  
    }).prop('disabled',true);    

     var emptyinputs = $(this).find('input').filter(function(){
     return !$.trim(this.value).length;  
    }).prop('disabled',true);    
});

You can disable empty fields (both select and input) so they don't get added as data, and for a custom form id.

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.