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¶2= 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?
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.
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.
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.
Try this,
Include jQuery and use following snippet.
$(document).ready(function(){
$("form").submit(function(){
$("input").each(function(index, obj){
if($(obj).val() == "") {
$(obj).remove();
}
});
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With