Go to URL from input dropdown - javascript

I have a dropdown on my website, where users can select different site-names.
Next to the dropdown I have a submit button.
I would like users to select a site-name, from the dropdown, and when they click on submit they should be redirected to a specific url, with the dropdown value appended.
<form id="form" method="get">
<option value="1">Website Name 1</option>
<option value="2">Website Name 2</option>
<option value="3">Website Name 3</option>
<button class="btn" type="submit">GO!</button>
</form>
Example case:
Users selects "Website Name 2"
User clicks "GO!" button
Site opens a new window with target "https://example.com/site/2"

There are many ways to do this. However you can try below way.
In the dropdown value add a complete url which you want to redirect to instead of just value and on button click redirect to that site.
Make sure button type is not 'submit' and attach a click event with a javascript funtion.
In the javascript function read the selected value from the dropdown and use
window.location.href
to redirect to that site.
function redirect() {
var value = document.getElementById("site").value;
window.location.href = value;
return ;
}
<form id="form" >
<select name="site" id ="site">
<option value="https://Google.com/1">Google</option>
<option value="https://stackoverflow.com/2">StackOverflow</option>
</select>
<button class="btn" type="button" onclick="redirect()">GO!</button>
</form>

There are multiple ways to accomplish this functionality. I prefer having minimal HTML and handling everything in the JavaScript. We will be using an EventListener to accomplish this in my example.
Change your HTML to this:
<form id="form" method="get">
<select id="selection">
<option value="1">Website Name 1</option>
<option value="2">Website Name 2</option>
<option value="3">Website Name 3</option>
</select>
<button class="btn" type="submit">GO!</button>
</form>
Then you can use simple JavaScript to accomplish what you want:
let url = "https://example.com/site/";
document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault();
let selection = document.getElementById('selection').value;
console.log(url + selection);
window.location.href = url + selection;
});
This answer assumes that all URLs follow the https://example.com/site/1 format. If not, you can change the value in the option tags to be the actual URL and remove the URL prefix from the JavaScript.

Related

Check string in select option

I have created with javascript and I get a result of a string.I get that result on my html code
<div id="results"></div>
Next,I want when I select for example Red to check if it is the the same thing (string), the select option - > Red with the string of this code
<div id="results"></div>
I was trying to do it but I failed.It is not working not even sure ,if I press the submit button I will send the string.
<div id="results"></div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="submit" value="results"/>
It appears that you want to check whether the selected option is equal to the text value of the div #results. You can achieve this effect like so:
$(document).ready(function(){
var select = $("select");
$("input[type=\"button\"]").click(function(){
var text = select.find(":selected").text();
if(text==$("#results").text()){
$("#results").html(text+" is equal!");
}else{
$("#results").html(text+" is not equal :(");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results">Red</div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="button" value="results"/>
</form>
A form is going to be Sending data somewhere, it would be best to remove the form, leaving the select and button elements. In the button add the code onclick='myFunction() ; when the button is clicked it will run the javascript function called myFunction(). Also you need to give the select a Id. I'm using selectInput
<script>myFunction() { document.getElementById('result').innerHTML = document.getElementById('selectInput').value;} </script>
Now when ever the button is pressed it will set the content of the div equal to the value entity in the selected select box option
You lack an action attribute.
<form method="post" action="path/to/file">
<select name="select">
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input type="submit" value="Get Results" />
</form>
Use a function, and a regular button. No form is needed.
<button onclick='func()'></button>
const func = () => {...}

How to set default value in input datalist and still have the drop down?

I am using the datalist HTML property to get a drop down inout box:
<input list="orderTypes" value="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The problem is that now I have to clear the input box to view all the drop down values. Is there a way to have a default value but still view all the values in the datalist when the drop down icon is clicked?
I have the same problem.
I just simple added placeholder with the default data.
In your example:
<input list="orderTypes" name="orderType" id="orderType" placeholder="Book" />
I listen submit event. If the input value is empty, I use Book as default value, otherwise I use the given value...
$("#mySubmitButton").click(() => {
// use event prevent here if need...
const orderType = $("#orderType").val() || "Book";
console.log(orderType);
});
I know of no way to do this natively. You could make a "helper" div to use when the input field has value. I couldn't hide the native drop down so I renamed the ID. Uses jQuery.
html
<input list="orderTypes" id="dlInput">
<div id="helper" style="display:none;position:absolute;z-index:200;border:1pt solid #ccc;"></div>
<datalist id="orderTypes" style="z-index:100;">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
script
$(function(){
// make a copy of datalist
var dl="";
$("#orderTypes option").each(function(){
dl+="<div class='dlOption'>"+$(this).val()+"</div>";
});
$("#helper").html(dl);
$("#helper").width( $("#dlInput").width() );
$(document).on("click","#dlInput",function(){
// display list if it has value
var lv=$("#dlInput").val();
if( lv.length ){
$("#orderTypes").attr("id","orderTypesHide");
$("#helper").show();
}
});
$(document).on("click",".dlOption",function(){
$("#dlInput").val( $(this).html() );
$("#helper").hide();
});
$(document).on("change","#dlInput",function(){
if( $(this).val()==="" ){
$("#orderTypesHide").attr("id","orderTypes");
$("#helper").hide();
}
});
});
jsFiddle
Is this what you trying to do?
var demoInput = document.getElementById('demoInput'); // give an id to your input and set it as variable
demoInput.value ='books'; // set default value instead of html attribute
demoInput.onfocus = function() { demoInput.value =''; }; // on focus - clear input
demoInput.onblur = function() { demoInput.value ='books'; }; // on leave restore it.
<legend>(double) click on the input to see options:</legend>
<input list="orderTypes" id="demoInput">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
The only "problem" here is that in order to see the options the user have to click the input again so it's like "double-click the input to see options".
Hope that helps.
I would use input's placeholder attribute along with a Javascript code that'll make sure that the field isn't empty upon submission.
Obviously this is just an example, you'll have to modify the submission event.
document.getElementById('submitButton').addEventListener('click', function() {
let inputElement = document.getElementById('myInput');
if (!inputElement.value) {
inputElement.value = 'Book';
}
});
<input id="myInput" list="orderTypes" placeholder="Book">
<datalist id="orderTypes">
<option value="Book">
<option value="Copy">
<option value="Page">
</datalist>
<input id="submitButton" type="submit">
I've menaged to get what You described with just <select> + <option> tags instead of <input> + <datalist>:
<select name="sortBY">
<option value="Book">Book</option>
<option value="Copy">Copy</option>
<option value="Page">Page</option>
</select>
Putting it all inside <form></form> tags will send it eg. with POST method with $_POST['sortBY'] value.
If this helps at all:
$('#grouptext').val($('#grouplist option#48').attr('value'));
where '#grouptext' is your text input to which your datalist '#grouplist' is attached, and #48 is the ID you're looking to "pre-select".
here's what my data list looks like, for clarity
worked for me.
In Chrome's console it shows up like this with "option#115", which corresponds to the correct text in the datalist for that "id" (being 115)
set id for your input and with js set default value
<script>
setTimeout(() => {
document.getElementById('orderTypes').value = "Book";
}, 100);
</script>

Changing form action based on select value - with JavaScript

I have a form that I wish to change the action of, depending on what value a user selects in a drop down box.
The example code below shows each option value, I want to change the form action to whatever option value is chosen on a button press, how can I do this with JavaScript?
<form name ="form1" action="VariableFormAction" method ="post" target="_blank">
<select name="formchoice">
<option value="/formaction1">function 1</option>
<option value="/formaction2">function 2</option>
<option value ="/formaction3">function 3</option>
</select>
<input type="submit" value="Go" class="button">
</form>
In order to do this you need to specify an onSubmit JavaScript event handler on the form that retrieves the value of the select list and updates the form action.
You can do this using the following code.
//Add onSubmit() event handler to form to call JavaScript method when the form is submitted.
<form name ="form1" onSubmit="actionOnSubmit()" method ="post" target="_blank">
<select id="formchoice" name="formchoice">
<option value="/formaction1">function 1</option>
<option value="/formaction2">function 2</option>
<option value ="/formaction3">function 3</option>
</select>
<input type="submit" value="Go" class="button">
</form>
<script>
function actionOnSubmit()
{
//Get the select select list and store in a variable
var e = document.getElementById("formchoice");
//Get the selected value of the select list
var formaction = e.options[e.selectedIndex].value;
//Update the form action
document.form1.action = formaction;
}
</script>
Note, for this to work you will need to make sure the select list has an id as you are using the document.getElementById[] JavaScript method to retrieve the value of the control.
You could also call the JavaScript in the OnChange() event of the control. The issue with this is that it implies that the value has changed before the form is submitted. If the user simply left the default select list value it is possible that the OnChange() event would never fire.
You can try like following.
function selectChanged(ctrl) {
var val = ctrl.value;
var frm = document.getElementById('form1');
frm.action = val;
}
<form id="form1" name="form1" action="/formaction1" method="post" target="_blank">
<select name="formchoice" onchange="selectChanged(this)">
<option value="/formaction1">function 1</option>
<option value="/formaction2">function 2</option>
<option value ="/formaction3">function 3</option>
</select>
<input type="submit" value="Go" class="button">
</form>
Use on change attribute.
<select name="forma" onchange="location = this.value;">
<option value="Home.php">Home</option>
<option value="Contact.php">Contact</option>
<option value="Sitemap.php">Sitemap</option>
</select>

Button to add selected="selected" from outside form

I am using laravel, and trying to integrate some jquery, which I am not very good at.
I have a multiple select box with potentially lots of options, based on database values.
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
The user can select tools directly from the select box, but this can be a huge list and therefore I am also displaying a search field below the select box to
search the database of tools so the user can see more info about the tool, and then decide if he wants to include it.
Currently the user has to first search, then find the entry in the select box and select it.
I want a faster solution with a button next to the info about the tool, that automatically adds selected="selected" to the correct option in the select box above.
I tried
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$("div.toolselect select").val(id);
}
But that erased all the other other selected fields.
Any ideas would be appreciated.
Try using jQuery's prop function:
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$('.toolselect select option[value="'+ id +'"]').prop('selected');
}
</script>
For a multi-select, the value is an array of all the selected items. You're just setting the value to a single item, which is treated as an array of one element, so all the other selections get discarded.
So you should get the old value, add the new ID to it, and then set that as the new value.
function addselect(id) {
$('.toolselect select').val(function(i, oldval) {
oldval = oldval || []; // oldval = null when nothing is selected
oldval.push(id);
return oldval;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
<input type="button" value="Select 1" onclick="addselect('1')"/>
<input type="button" value="Select 2" onclick="addselect('2')"/>
<input type="button" value="Select 3" onclick="addselect('3')"/>
Instead of using this :
addselect = function (id){
$("div.toolselect select").val(id);
}
Try this :
addselect = function(id) {
var temp = [];
var arr = $('select').val();
for(i=0;i<arr.length;i++){
temp.push(arr[i]);
}
temp.push(id);
$("div.toolselect select").val(temp);
}
This way your previous selection is preserved, and the new selection is appended to the previous selection.
Hope this helps.

goto url using javascript on Select box | DropDown box

I have the below javascript function to go to the selected box value url.
function go(x) {
alert(x);
location = x.value;
}
I cannot use getElementById
There may be more than 1 select box as the user differs
I wrote a php to print all the selectbox inside a form and div
<div class="styled-select">
<form name="menu">
<select id=Admission onchange=go(this)>
<option value=/admission>Add Existing Students</option>
</select>
<select id=Student onchange=go(this)>
<option value=www.bing.com>Student Details</option>
</select>
</form>
</div>
All suggestions are welcome.
You don't access the value of the element properly. Use this instead:
function go(x) {
location = x.options[x.selectedIndex].value;
}
You also won't get an onchange event for a <select> with only a single option ever.

Categories