My usage is simple, I have a simple select element on my page.
<select id="project-dropdown">
<option data-url="/constructions/6">Test 1</option>
<option data-url="/constructions/7">Test 2</option>
</select>
And in Javascript:
$('#project-dropdown').change(function() {
var url = $(this).find(':selected').data('url');
window.location = url;
});
This event works fine except when I want to go to the first option. The page starts out with the first element selected so I can't fire the changed event on it.
Any suggestions?
Does a little hack like this works for you?
HTML Part:
<select id="project-dropdown">
<option data-url="#">Select a value</option>
<option data-url="/constructions/6">Test 1</option>
<option data-url="/constructions/7">Test 2</option>
</select>
JS Part:
$('#project-dropdown').change(function() {
var url = $(this).find(':selected').data('url');
if(url !== "#")
window.location = url;
});
JsFiddle
Just call $('#project-dropdown').change(); after change binding. Like this:
$('#project-dropdown').change(function() {
var url = $(this).find(':selected').data('url');
window.location = url;
});
$('#project-dropdown').change();
Here is its JSFiddle.
I recommend you change your HTML to:
<select id="project-dropdown" size=2>
<option data-url="/constructions/6">Test 1</option>
<option data-url="/constructions/7">Test 2</option>
</select>
By setting size=2 you override the default value of 1, which causes the list to be displayed as a single line, with the initial option pre-selected (with the side-effect that clicking it does not trigger a change event).
Setting size to 2 or more causes the options to be displayed in a list that is size lines high, with no initial selections, so that the user can choose any of the options, including the first.
Related
So I am making two dropdowns. One is dependent on the other one, as in when you choose an option in the first dropdown, the values in the other should change. I am rendering my form with Symfony3.4, so I do not have much control over it. (I do not think I can add dynamic class names/value names to it). If it is relevant, I am using Bulma css framework.
Here is what my selectboxes look like:
states:
<select name="state" id="stateSelect">
<option value="1">Lagos</option>
<option value="2">Abuja</option>
<option value="3">Rivers</option>
<option value="4">Ogun</option>
<option value="5">Oyo</option>
<option value="6">Anambra</option>
<option value="7">Enugu</option>
<option value="8">Akwa Ibom</option>
<option value="9">Adamawa</option>
...
<option value="37">Zamfara</option>
</select>
LGA (local government areas):
<select id="lgaSelect" name="areas_registration[lga]">
<optgroup label="Lagos">
<option value="1">Abule Egba</option>
<option value="2">Agege</option>
<option value="3">Ajah</option>
<option value="4">Alimosho</option>
<option value="5">Amuwo Odofin</option>
...
</optgroup>
<optgroup label="Abuja">
<option value="38">Apo</option>
<option value="39">Asokoro</option>
<option value="40">Central Area</option>
<option value="41">Chika</option>
<option value="42">Dakibiyu</option>
...
</optgroup>
....35 more optgroups
</select>
My goal is when a user chooses an option from States dropdown, the LGA dropdown should only have options relevant to the selected state. I am using optgroup label for this. What I tried in my javascript is that when the page loads, I clone the LGA dropdown, hide it, call it lgaSelectSeed and use it for seeding the original LGA dropdown: (#hiddenLgas is just an empty div)
$(function () {
var stateSelect = $("#stateSelect") || null;
var lgaSelect = $("#lgaSelect") || null;
var hiddenLga = $("#hiddenLgas") || null;
$(hiddenLga).html(lgaSelect.clone().prop('id', 'lgaSelectSeed'));
stateSelect.change(function () {
var select_class = $(this).find('option:selected').text();
var options = $(lgaSelectSeed).find('optgroup[label="' + select_class + '"]');
$(lgaSelect).html(options.children());
}
This works but there is a bug in it. If you select random options in the state dropdown, and then go up and select Lagos or Abuja, the LGA dropdown becomes blank. I have been trying to figure out for a few days why this is happening, but still cant. Is there any jquery plugin to handle this instead?
DEMO: https://jsfiddle.net/gafyvbL9/
How to replicate the bug: In the states dropdown (left), choose Lagos. Then choose Anambra. Then choose Lagos again, then choose Anambra. You can see that the LGA dropdown (right) becomes empty. Why is this happening? Thanks in advance
Make a clone of the stored options so you don't remove the originals from $(hiddenLga)
Change:
$(lgaSelect).html(options.children());
To
$(lgaSelect).html(options.children().clone());
Playing with your fiddle, I think the issue is when you perform $(lgaSelect).html(), you're deleting all of the information stored there. Try storing that outside of your handler.
let $options = $('#lgaSelect').clone();
$("#stateSelect").on('change',function() {
let state = $(this).find('option:selected').text();
$("#lgaSelect").html($options.find(`optgroup[label="${state}"]`).html());
});
EDIT:
Notice the double quote in optgroup[label="${state}"]. This prevents issue with states that contain a space, like Akwa Ibom.
Everything works as it should. Just having trouble getting both select box values carried with the hash event listener. For now I only have #search_region in there and it carries over as it should. I need #search_region and #search_categories in there.
Output displays www.example.com#135&140. The link www.example.com#135&140 as is should be able to be copied to a new tab and keep both values chosen selected basically.
Any ideas on how I should go about this one?
<select name="search_region" id="search_region" class="search_region">
<option value="0">All Regions</option>
<option class="level-0" value="135">Camps Bay</option>
<option class="level-0" value="136">Cape Town</option>
<option class="level-0" value="137">Durbanville</option>
<option class="level-0" value="139">Hermanus</option>
<option class="level-0" value="138">Langebaan</option>
</select>
<select name="search_categories" id="search_categories" class="search_categories">
<option value="">Select Category</option>
<option class="level-0" value="140">140</option>
<option class="level-0" value="141">141</option>
</select>
<script type="text/javascript">
// ADDS selected values to URL
$(function(){
var url = '';
$('#search_region').change(function () {
url = $(this).val();
window.location.hash = url;
console.log(window.location.hash);
});
$('#search_categories').change(function () {
if(url !==''){
window.location.hash = url+"&"+$(this).val();
}
console.log(window.location.hash);
});
});
// carries selected value over to new browser or new tab. *where the help is needed*
window.addEventListener('hashchange', fn, false);
window.onload = fn; // fire on pageload
function fn() {
$('#search_region').val(window.location.hash.replace('#', ''));
console.log("hash = " + window.location.hash);
}
</script>
This is an add on from a previously asked question. Link below
Displaying two seperate select box values in a URL
Its just a matter of checking if there are two hashes and splitting it and setting the values to the select.
function fn() {
var values = window.location.hash.replace('#', '').split('&')
$('#search_region').val(values[0]);
if (values.length > 1){
$('#search_categories').val(values(1));
}
console.log("hash = " + window.location.hash);
}
Your code expects that the second element is only ever changed after the first one is. You should consider using the same event handler on both elements and constructing the right URL no matter which element receives the event. Remove the half-global variable url.
Secondly, in fn, you have to .split() the hash to separate the two values and assign them to their respective elements.
I have two selectmenus, one of which $('#parent') relates to certain options in the $('#members') menu (related through a data attribute in their HTML). I have a function to limit the choices in 'members' where they relate to the choice selected in the parent menu.
SCRIPT
$("#parent").selectmenu();
$("#members").selectmenu();
var allMembers = $('#members option'); // keep object list of all of the options for the select menu
$("#parent").on("selectmenuchange", function() {
var someMembers = [];
var id = $('#parent option:selected').data('id');
allMembers.each(function() {
if ($(this).data('parent-id') == id) {
someMembers.push($(this))
}
});
$('#members').empty().append(someMembers);
});
At the moment, this works, but only on the first selectmenuchange event - which is odd because using console.log() when the arrays are recreated in the function I can see that the correct have been selected each time, they just don't show in the menu on subsequent changes.
I can't figure out if this is a problem with selectmenuchange or empty().append()
HTML
<select name="members" id="members">
<option data-id="101" data-parent-id="1">Name1</option>
<option data-id="102" data-parent-id="1">Name2</option>
<option data-id="103" data-parent-id="1">Name3</option>
<option data-id="104" data-parent-id="2">Name4</option>
<option data-id="105" data-parent-id="2">Name5</option>
<option data-id="106" data-parent-id="3">Name6</option>
<option data-id="107" data-parent-id="3">Name7</option>
</select>
<select name="parent" id="parent">
<option data-id="1">Parent1</option>
<option data-id="2">Parent2</option>
<option data-id="3">Parent3</option>
</select>
Well the options were changing but it wasn't reflecting in the selectmenu created by plugin. So one of the way is you destroy it and re-initialize the selectmenu as below:
$('#members').html(someMembers).selectmenu('destroy').selectmenu();
DEMO
Instead of selectmenu('destroy') and re-initializing the select menu you can also use selectmenu('refresh'). Refreshing sounds nicer than destroying it each time.
I have updated the fiddle of Guruprasad Rao with the refresh:
fiddle
<select id="country_name" onchange="changeCounty();">
<option value="IND"> IND</option>
<option value="US">US</option>
<option value="JP">JP</option>
<option value="UK">UK</option>
</select>
i have the above code.
when i select one option it will do some changes to the page.but when i open the page in new tab of browser the already selected option reset. and default selected option set.How do i cop with this?
You need something to pass the value from one page to another, as tabs are by default totally separate pages.
One workaround could be something like this (using LocalStorage) :
// Save value when it is changed by user
function changeCounty(){
if(window.localStorage){
var inputValue = document.getElementById('country_name').value
window.localStorage.set('mySavedValueName',inputValue )
}
//..your original code
}
// Load value if it exists
window.addEventListener('load', function getContryFromLS(){
if(window.localStorage){
var lsvalue = window.localStorage.get('mySavedValueName')
if(lsvalue)
document.getElementById('country_name').value=lsvalue
}
}
Your Html code
<select id="country_name" onchange="changeCounty(this);">
<option value="IND"> IND</option>
<option value="US">US</option>
<option value="JP">JP</option>
<option value="UK">UK</option>
</select>
JQuery Code
$(function(){
var d=localStorage.getItem("selectval");
if(d!=null){
console.log(d);
$("#country_name").val(d);
}
$("#country_name").change(function(){
localStorage.setItem("selectval",$(this).val());
});
});
Demo Here
So here is my code
<select id="BVT STUFF" onChange="jumpTo(getSelected(this));">
<option>HardRock Catalog</option>
<option value="http://link">BVT WIKI</option>
<option value="http://link">BVT CALENDAR</option>
<option value="https://link">Sustainment</option>
<option value="link">UVerse Dispatch Servlet</option>
This is a tool that I created for my team.
My problem is that I have the list "Title" as the first option and tried to give it a null value but whenever it is selected it tries to open a page. i.e. HardRock Catalog
Is there anything I could do with this to allow the list title to really have no value?
I'll suggest to add value="" for the first option. Then in your jumpTo function check
<option value="">HardRock Catalog</option>
function jumpTo(url) {
if(url === "") return;
// other stuff here
}
You could add selected and disabled attributes.
jsfiddle
HTML
<option selected="selected" disabled>HardRock Catalog</option>
You may try this
HTML :
<select onchange="jumpTo(this)">
<option value='0'>HardRock Catalog</option>
<option value="http:\\google.com">Goto Google</option>
<option value="http:\\yahoo.com">Goto Yahoo</option>
</select>
JS :
function jumpTo(select)
{
if(select.value != '0'){
// code goes here
location.href = select.value;
}
}
DEMO.