Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit only non empty fields from Form

That is the form:

<form action="" method="GET">
<input type="text" name="para1">
<input type="text" name="para2">
<input type="submit" value="search">
</form>

Now when I fill out only the first field I get example.com/?para1=value&para2= But I just want it to be example.com/?para1=value because para2 don't contains value. How can I do this? Should be possible with JS or anything?

like image 350
Eddy Unruh Avatar asked May 08 '14 04:05

Eddy Unruh


People also ask

How do you stop an empty form submission?

Bookmark this question. Show activity on this post. When no value is provided to the roll input field an alert is produced by the empty() function but this empty value is still passed to retrive.

Can we submit form without form tag?

It is actually possible to "submit" a "form" without form-tags. what you need is an ajax-function, e.g. with jquery, which will get the values by id. But there is no reason not to use a form tho.

Do not submit form if field is empty jQuery?

One of the most used logic related to submitting a form is preventing sumbission if a field is empty. In this example we'll provide examples with source code how to prevent form submit in case of empty field. The main trick here is using . preventDefault() function to stop the submission.


2 Answers

Try this,

Include jQuery and use following snippet.

$(document).ready(function(){
    $("form").submit(function(){
        $("input").each(function(index, obj){
            if($(obj).val() == "") {
                $(obj).remove();
            }
        });
    });
});
like image 200
Rashmin Javiya Avatar answered Nov 05 '22 19:11

Rashmin Javiya


Something like this would be the plain javascript version:

<form id="theform" action="" method="GET" onsubmit="return removeEmpties()">
    <input type="text" name="para1"/>
    <input type="text" name="para2"/>
    <input type="submit" value="search"/>
</form>
<script>
  function removeEmpties() {
        var form = document.getElementById("theform");
        var inputs = form.children;
        var remove = [];
        for(var i = 0; i < inputs.length; i++) {
            if(inputs[i].value == "") {
                remove.push(inputs[i]);
            }
        }

        if(remove.length == inputs.length - 1)
          return false;

        for(var i = 0; i < remove.length; i++) 
          form.removeChild(remove[i]);
        return true;
    }
</script>
like image 23
Darius Houle Avatar answered Nov 05 '22 20:11

Darius Houle