I am trying to add a search feature based on a text input and a drop-down.
So I am trying to make it work with the following form fields:
- Text input {text_1}
- Drop-down (2 options)
- Submit button
If first option is selected in the drop-down the form should be submitted to https://url1/?={text_1}
, if second option is selected it should be submitted to https://url2/?={text_1}
.
I have written so far:
<form>
<input type="text" id="text_1" name="text_1" value="test" data-alias="" >
<select id="selectlist_1" name="selectlist_1" data-alias="" >
<option value="option_1" >Option_1</option>
<option value="option_2" >Option_2</option>
</select>
<button type="submit" id="button_1" name="button_1" >Submit</button>
</form>
Otherwise, there is also this example: https://hii.com/careers/
CodePudding user response:
I give you an example:
<script>
function go(v){
if (v.url.value===1){
v.action="http://www.google.com"
}else {
v.action="http://www.apple.com"
}
}
</script>
<form onsubmit="go(this)">
<input type="text" name="text_1" value="txt">
<select name="url">
<option value="1">Google</option>
<option value="2">Apple</option>
</select>
<input type="submit" value="submit">
</form>
CodePudding user response:
Augment a simple form with the controls you want, with a script that sets up a behaviour where the form's action
attribute value changes with the selection in the drop-down control:
<form>
<input name="foobar" />
<select name="fruit">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
</select>
<script>
(script => {
const fruit_control = script.closest("form").elements.fruit;
fruit_control.addEventListener("change", ev => {
ev.target.form.action = ({
"apples": "https://url_1",
"oranges": "https://url_2"
})[ev.target.value];
});
})(document.currentScript);
</script>
</form>
The value of the text input control will be sent with the query string, i.e. as ?foobar=...
at the end of the URL, as the form is submitted, to the URL that's correspondent with the option selected in the drop-down.
Whether you have a submit button at the end of the form, or not, makes no difference to the behaviour of the form because a form may be submitted even without a submit button.