Parameterise DropDown values as URL using JavaScript? - javascript

I have the code below. It has 3 dropdown option values. Currently, on change of dropdown selection an alert is thrown.
Now, I want to achieve the following: parameterise my dropdown values as URL's, so that i.e. when I enter the following URL in a browser: file://test.ds.waq.cb.uk/anywhere/UserData/PSStore02/u1718987/Desktop/new.html with ?mySelect=BMW at the end, then the browser opens the dropdown with the value BMW populated.
Or if I enter file://test.ds.waq.cb.uk/anywhere/UserData/PSStore02/u1718987/Desktop/new.html?mySelect=Audi, the browser opens the dropdown with Audi populated.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Volvo">Volvo
</select>
<p id="demo"></p>
Need to modify below script, to parameterise dropdown selection as URL, please advise.
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
</body>
</html>

You can easily fetch the url's parameter using expressions and some conditions to select the option. Change mySelect value in url to check it.
JAVASCRIPT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
$(document).ready(function(){
var data = getUrlVars()["mySelect"];
if(data == "Audi"){
$('select').prop('selectedIndex', 0);
}
else if(data == "BMW"){
$('select').prop('selectedIndex', 1);
}
else if(data == "Volvo"){
$('select').prop('selectedIndex', 2);
}
});
HTML:
<select>
<option class="Audi">Audi</option>
<option class="BMW">BMW</option>
<option class="Volvo">Volvo</option>
</select>

use this answer to extract search queries. Then just set value on load with the proper value.
<script>
function setValue(value) {
document.getElementById("mySelect").value = value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
UPDATE
to have both in the same script.
<script>
function setValue(value) {
document.getElementById("mySelect").value = value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
let urlParams = new URLSearchParams(window.location.search);
setValue(urlParams.get('mySelect');
</script>

You can read url params once select box loads, see below code
HTML:
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()" onload="setMySelect()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Volvo">Volvo
</select>
<p id="demo"></p>
<script>
function setMySelect() {
var urlParams = new URLSearchParams(window.location.search);
var mySelect = urlParams.get('mySelect');
if(mySelect)
document.getElementById("mySelect").value = mySelect;
}
function myFunction() {
var x = document.getElementById("mySelect").value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
</body>
</html>

You could try the following.
var url = new URL(window.location);
var params = new URLSearchParams(url.search.slice(1));
for (let [key, value] of params.entries()) {
if(params.has(key) && key == "mySelect") {
document.getElementById(key).value = value;
}
}
document.getElementById("mySelect").addEventListener("change", (e) => {
params.set("mySelect",e.target.value);
url.search = params.toString();
let new_url = url.toString();
window.location.assign(new_url);
})

I needed the following window.onload as this function was not getting loaded.
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()" onload="setMySelect()">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Volvo">Volvo</option>
</select>
<p id="demo"></p>
<script>
<!-- function setMySelect() { -->
window.onload = function() {
var urlParams = new URLSearchParams(window.location.search);
var mySelect = urlParams.get('mySelect');
if(mySelect)
document.getElementById("mySelect").value = mySelect;
}
function myFunction() {
var x = document.getElementById("mySelect").value;
alert (document.getElementById.innerHTML = "You selected: " + x);
}
</script>
</body>
</html>

Related

Creating A select element and if statement to display different href

I am trying to create a drop down menu and then based on selection display a clickable link to book time with each Customer service manager ... sorry for the awful code below i pieced it together from very old knowledge and google
\\
</select>
<button onclick="message()">book a time </button>
<SCRIPT>
function message() {
var s = document.getElementById('item1');
var item1 = s.options[s.selectedIndex].value;
let bookt;
if (item1 == 1)
{ document.getElementById("demo").innerHTML= Book Kim ;
}
else if (item1 == 2)
{ bookt="ibrahim link"; }
else if (item1 == 3) {
bookt= ;}
else if (item1 == 4) {
bookt="Steff Link";}
}
</SCRIPT>
<p id="demo"></p>
</body>
</html>
\\
The following code should do it:
const select = document.getElementById('select')
const links = ['https://google.com/', 'https://apple.com/', 'https://microsoft.com/']
var selectedItem = links[0]
function update() {
const item = parseInt(selectedItem)
document.getElementById('link').innerHTML = `book a time</button>`
}
<!Doctype html>
<html>
<body>
<select id='select' onchange='selectedItem = this.value;update()'>
<option selected hidden>Choose a person</option>
<option value='1'>Person 1</option>
<option value='2'>Person 2</option>
<option value='3'>Person 3</option>
</select>
<div id='link'><button>Please choose an option!</button></div>
</body>
</html>
The links array contains the links to each page that you would like to send the user to for the selected person, who is stored inside of the dropdown menu.

Getting result out of a function into a usable variable?

So I have a simple HTML file that I want to have a select option drop down menu. I have made that when a selection is made the page reloads retaining the option but I can't get the result outside of the function.
<!doctype html>
<html>
<head>
</head><body>
<select id="mySelect" onchange = "getSelectValue();">
<optgroup label="Working">
<option value="rage.zip">Streets of Rage</option>
<option value="quest.zip">Money Quest</option>
</optgroup>
</select>
<div style="width:640px;height:480px;max-width:100%">
<script type="text/javascript">
window.addEventListener('load', function(){
if (localStorage.pick) {
var sel = document.querySelector('#mySelect');
sel.value = localStorage.pick;
}
});
function getSelectValue(){
var sel = document.querySelector('#mySelect');
localStorage.pick = sel.value;
location.reload();
return sel.value;
}
EJS_player = '#game';
EJS_gameUrl = ; // Url to Game rom
EJS_gameID = 4; // ID in your website, required for netplay.
EJS_core = 'segaMD';
</script>
<script src="https://www.emulatorjs.com/loader.js"></script>
</body>
</html>
My issue is the select option result is in the sel.value. I need that value to EJS_gameUrl = .
So if the option 1 is select which is rage.zip then it should be filled in the EJS_gameUrl = "rage.zip"
Im just having trouble with getting that result out of the function . I would prefer to define it to a variable and just add the variable in the EJS_gameUrl = x; or similar. How can I go about this?
See Storing the information you need — Variables, Storage.setItem and Storage.getItem.
Your code should be something along the lines of:
const EJS_player = '#game';
let EJS_gameUrl = ''; // Url to Game rom
const EJS_gameID = 4; // ID in your website, required for netplay.
const EJS_core = 'segaMD';
window.addEventListener('load', function() {
const storedValue = localStorage.getItem('mySelect');
if (storedValue) {
var sel = document.querySelector('#mySelect');
sel.value = storedValue;
EJS_gameUrl = storedValue;
}
});
function getSelectValue() {
localStorage.setItem('mySelect', this.value);
location.reload();
}
console.log(EJS_gameUrl)
<select id="mySelect" onchange="getSelectValue();">
<optgroup label="Working">
<option value="rage.zip">Streets of Rage</option>
<option value="quest.zip">Money Quest</option>
</optgroup>
</select>

Trigger the event when selected the same value in dropdown?

Issue: I have a dropdown with a list of years in it with nothing selected, the user selects "1976", I run a function. If the user clicks on the dropdown again and selects "1976" AGAIN, I want to run the function again.
$('select').on('change', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
});
Simple JS
---------
<html>
<head>
<script>
var prevIndex = "";
function onSelect()
{
var currIndex = document.getElementById("ddList").selectedIndex;
if( currIndex > 0 )
{
if( prevIndex != currIndex )
{
alert("Selected Index = " + currIndex);
prevIndex = currIndex;
}
else
{
prevIndex = "";
}
}
}
</script>
</head>
<body>
<select id="ddList" onClick="onSelect()">
<option value="0">Select Me</option>
<option value="1">List1</option>
<option value="2">List2</option>
<option value="3">List3</option>
</select>
</body>
</html>
This basic idea should work using jQuery using click event:
$('#yourselect').click(function() {
console.log("your function");
});
A simple if statement could prevent firing off the function when initially clicking the select element.
The closest functionality that you're seeking that I can think of is the following:
-HTML-
<select class="opt-evt">
<option value="" selected="selected"></option>
<option value="1976">1976</option>
</select>
-jQuery-
$(document).ready(function(){
$('.opt-evt').change(function(){
$(this).blur();
}).blur(function(){
console.log($(this).find('option:selected').val());
});
});
The caveat is that if the user selects '1976' again, the desired event only gets fired onBlur.
http://jsfiddle.net/4G9Jf/
mouseup event should do the trick:
$('select').mouseup(function(){
console.log("hue");
});
http://jsfiddle.net/5Fcgr/
note that this will be triggered twice when a new value is selected in the listbox. Once when opening the options, and once when selecting an option.
I have fixed as below,
<html>
<head>
<script>
function onSelect()
{
var dd = document.getElementById('ddList');
var txtTerms = document.getElementById('selValue');
var storeLstSlct = document.getElementById('checkIndx');
var slctdValue = '';
if(dd.selectedIndex == 0)
{
return false;
}else if(storeLstSlct.value == dd.options[dd.selectedIndex].value)
{
storeLstSlct.value = 'abcd';
return false;
}else
{
slctdValue = dd.options[dd.selectedIndex].value;
if(txtTerms.value != '')
txtTerms.value = txtTerms.value + ' , ' + slctdValue;
else
txtTerms.value = slctdValue;
storeLstSlct.value = slctdValue;
}
}
</script>
</head>
<body>
<select id='ddList' onclick='onSelect()'>
<option value='0'>Select Me</option>
<option value='One'>List1</option>
<option value='Two'>List2</option>
<option value='Three'>List3</option>
</select>
<input type='hidden' name='checkIndx' id='checkIndx' />
<input type='text' name='selValue' id='selValue' />
</body>
</html>

JavaScript code for getting the selected value from a combo box

Can any one give me a sample code that gets the selected value from an existing combo box?
I have this code but its not doing anything:
function check ()
{
var e = document.getElementById("ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);​
heres a img of the code
and the code
<select id="ticket_category_clone" name="ticket[category]" hdpp="ticket_category">
<option value=""></option><option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Rede" selected="selected">Rede</option>
<option value="Pedidos">Pedidos</option>
<option value="Formação/Dúvida">Formação/Dúvida</option>
<option value="Outro">Outro</option><option value="#edit_categories#">Edit Categories...</option></select>
what i want its find a way to get the selected value fo that combobox
There is an unnecessary hashtag; change the code to this:
var e = document.getElementById("ticket_category_clone").value;
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);​
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>

javascript with html select box

I have select box with default value,i want to retrieve default value and changed value using javascript,Below is my Html Select box:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST()">
<OPTION ID="1" VALUE="TEST1" SELECTED/>
<OPTION ID="2" VALUE="TEST2"/>
</SELECT>
Regards,
Raj
You can set custom attribute of the element in the onload event of the document:
window.onload = function() {
var oDDL = document.getElementById("TEST");
oDDL.setAttribute("default_value", oDDL.value);
};
Then to read it:
function Test() {
var oDDL = document.getElementById("TEST");
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Complete code and test case: http://jsfiddle.net/yahavbr/MbnH7/
Edit: to support more than one drop down, first pass reference in the onchange event like this:
<select id="TEST" name="TEST" onchange="Test(this);">
Then set the custom attribute in a loop:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("default_value", oDDL.value);
}
};
And the test function also need minor change as it's not getting the drop down as argument:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strDefaultValue = oDDL.getAttribute("default_value");
alert("Default value is: " + strDefaultValue + "\n Current value is: " + strCurrentValue);
}
Updated test case: http://jsfiddle.net/yahavbr/MbnH7/1/
Edit II: to show the previously selected value some name changes are required, plus storing the value every time it's changing. The onload becomes this:
window.onload = function() {
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
oDDL.setAttribute("previous_value", oDDL.value);
}
};
(Only change is the custom attribute name)
And the function becomes:
function Test(oDDL) {
var strCurrentValue = oDDL.value;
var strPreviousValue = oDDL.getAttribute("previous_value");
alert("Previous value is: " + strPreviousValue + "\n Current value is: " + strCurrentValue);
oDDL.setAttribute("previous_value", strCurrentValue);
}
(Name change plus setting the custom attribute)
Updated and hopefully final test case: http://jsfiddle.net/yahavbr/MbnH7/4/
why not have the onfocus event (vs. onload) store the current value. one solution might be to do something like this:
$(t).data("prev",$(t).val())
and then have the onchange use that:
var oldVal = $(t).data("prev");
thus when someone clicks on, or tabs into, the ui element it stores the current state, and then can use that if there is a resulting change. also it would need to change the value if the change was accepted so that if focus was not changed (ie: they stayed in the pulldown and changed the value again) and they changed their mind and chose another option that the state was preserved.
many of the examples that i have seen of this store state in a that seemed to be vulnerable to change/events elsewhere.
HTML:
<SELECT ID="TEST" NAME="TEST" ONCHANGE="TEST(this)">
<OPTION ID="1" VALUE="TEST1" SELECTED>TEST 1</OPTION>
<OPTION ID="2" VALUE="TEST2">TEST 2</OPTION>
</SELECT>
javascript:
// store currently selected value
var previousValue = document.getElementById('TEST').value;
function TEST(e) {
alert('old value = ' + previousValue);
alert('new value = ' + e.value);
// store new value
previousValue = e.value;
}
example here
EDIT - I answered wrong before - Here's a sample HTML page that does it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
function showOptionValue(oSelect) {
var def;
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected){ //this option's defaultSelected property is set to true (from HTML: selected="selected")
def = oSelect[i].text; //or .value
}
var sel;
sel = oSelect[oSelect.selectedIndex].text;
alert (sel + ' : ' + def);
}
function resetSelect(oSelect) {
for (var i=0; i<oSelect.options.length; ++i) //loop through select options
if (oSelect.options[i].defaultSelected) //this option's defaultSelected property is set to true (from HTML: selected="selected")
oSelect.options[i].selected = true; //so, set its selected property to true, selecting it
showOptionValue(oSelect); //reset status
}
</script>
</head>
<body>
<form>
<!-- call handler function, pass Select object (represents drop-down list) -->
<SELECT NAME="cbo" onchange="showOptionValue(this)">
<OPTION VALUE="not_default">Not DEFAULT VALUE</OPTION>
<OPTION VALUE="1">Small</OPTION>
<!-- default value, preselected -->
<OPTION VALUE="2" selected="selected">Medium</OPTION>
<OPTION VALUE="3">Large</OPTION>
</SELECT>
<!-- call handler function, pass Select object using its name as a variable -->
<input type="button" value="Reset Drop-down" onclick="resetSelect(cbo)">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script type="text/javascript">
function fn(){
var select = document.getElementById("selectbox");
alert(select.options[select.selectedIndex].value)
}
</script>
</head>
<body>
<header style="margin-left: 50%;">Welcome</header>
<select id="selectbox">
<option value="number 01">Number 01</option>
<option value="number 01">Number 02</option>
<option value="number 01">Number 03</option>
<option value="number 01">Number 04</option>
</select>
<button style="margin-top:10px; margin-left:15px;" onclick="fn()">Click me</button>
</body>
</html>

Categories

Resources