Reputation: 87
I am writing a search box in HTML that takes the user input and append it to the URL as a parameter. The code of the form looks like this.
<form name="form" action="" method="get">
<input type="text" name="id" id="idresponse">
<input type="submit" value="Submit">
</form>
This will bring the user from example.com/test.html
to example.com/test.html?id=12345678
assuming they entered 12345678
at the text box.
However, if the user inputted nothing and clicked Submit, they will be brought to example.com/test.html?id=
, which I don't want. How can I modify the code so that the form knows that a certain field is left blank and do not send the parameter with the URL? In this case, the desired URL would be example.com/test.html
.
edit 20210405 2057 changed the id of the input from idresposne
to idresponse
to avoid confusion
Upvotes: 1
Views: 1064
Reputation: 87
The so-called URL parameters is the querystring of the URL.
The following code does not use jQuery, but achieves a similar effect. (written by RobG)
<form name="form" onsubmit="disableEmptyInputs(this)" action="" method="get">
<input type="text" name="id" id="idresponse">
<input type="submit" value="Submit">
</form>
<script>
function disableEmptyInputs(form) {
var controls = form.elements;
for (var i=0, iLen=controls.length; i<iLen; i++) {
if (controls[i].value == '') controls[i].disabled = true;
}
}
<script>
This will remove all the parameters but the ? will still trail the URL. i.e. the URL will be example.com/test.html?
instead. However, this does not matter because they both point to the same address.
Refer to these links (kindly provided by Progman) for other ways of doing this, including using jQuery.
Thanks.
Upvotes: 2