I’m wondering what action url and name term I’m suppose to use if the search term is in the middle of the URL?
For example, the HTML code below allows me to input text and when I press enter or the button, it automatically sends me to the website with the search term already entered.
<form action="https://www.google.com/search?q=goog">
<input id="Google" type="text" name="q">
<button>Search on Google</button>
</form>
But I don’t get what use if it’s an URL like this: https://youglish.com/pronounce/朋友/chinese
I tried this and I’m only sent to the Chinese site, but the search term wasn’t searched
<form action="https://youglish.com/pronounce/../chinese">
<input id="Youglish" type="text" name="pronounce">
<button>Search on Youglish</button>
</form>
Or something like in Google images….
<form action="https://www.google.com/search?q=..=img">
<input id="Google Images" type="text" name="q=..=img">
<button>Search on Google Images</button>
</form>
It just takes me to the Google Images website, and not with the search term entered.
3
Answers
Assuming that in this example:
You meant to add the search term to where the
...
is, the short answer is that you can’t do this with just HTML, you need Javascript as well.The third example should just work, because it does use
?q=
. Using HTML forms query parameters get added to the URL after the?
, and the order generally doesn’t matter.The google example has a bunch of other parameters that you can individually add to your form with
<input type="hidden">
for each parameter, however for google specifically you can also ignore all those.This doesn’t work how you think it works.
Your form submission is creating an HTTP GET request and constructing GET parameters from your form data. If you type
fox
into the field namedq
, you will get?q=fox
. If there is a second field namedx
with valuey
, you get?q=fox&x=y
.With Google image search, the solution is simply to add a second, hidden field that will cause
&tbm=isch
to be appended to the URL string:But all of this only works because Google uses GET parameters.
Can’t be done with pure HTML, you need JavaScript. Something like:
I think you can’t do that with just an HTML form, because when you send the form, the inputs values are added to the action url so in your example:
The resulting url would be:
and checking the chinese browser, the url you need is:
So you can use javaScript to prevent the form event and then create the url and open it as you wish.
Here is the documentation of Event.preventDefault(), it contains some examples: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault