<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
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.
I am using Jquery chosen plugin and it's working fine. I have used this plugin in my one of the module. My dropdown values are something like that:
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
It's working fine. But problem is that when user select first option and then try to change third option onchange event does not fire because both options values are same. Is there any way to call onchange event every time if values are same or differ ?
Options values is a unique key of item so it's repeated in dropdown. Dropdown value is duplicate we have allowed to use same item in others module
I saw your implementation and it is working fine in code pen here is the link no need to change anything
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
var get_data =function(){
alert("saas")
}
http://codepen.io/vkvicky-vasudev/pen/dXXVzN
Try this
$('#itemcode').click(function() {
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="itemcode">
<option value="1">ITEM001-A</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001-B</option>
<option value="3">ITEM003</option>
</select>
Edit: This doesn't work. Sorry!
You could add a data attribute that differs for each element, for example:
<select id="itemcode" onchange="get_data()">
<option value="1" data-id="1">ITEM001</option>
<option value="2" data-id="2">ITEM002</option>
<option value="1" data-id="3">ITEM001</option>
<option value="3" data-id="4">ITEM003</option>
</select>
If you're using Rails or another framework to generate the <option> tags, it should be easy to add an incremental id to each element.
There is no way to fire get_data() with your current data.
The solution below is more of a hack. When you populate the options, prepend the value with something unique.
Eg.
<select id="itemcode" onchange="get_data()">
<option value="1_1">ITEM001</option>
<option value="2_2">ITEM002</option>
<option value="3_1">ITEM001</option>
<option value="4_3">ITEM003</option>
</select>
Thus your get_data() method will be called everytime. And in your get_data() method, split the value using underscore _ and you can get the actual value there.
function get_data(){
var actualValue=$(this).val().split("_")[1];
//do other processing
...
}
You can use other characters like $, or anything you like, instead of _
Ideally you want to change the data coming from the backend so that you don't get duplicate data. However if this is not possible, another approach would be to sanitise the data before putting it in the select. E.g
https://jsfiddle.net/vuks2bpt/
var dataFromBackend = [
{key:1,
value: "ITEM0001"
},
{key:2,
value: "ITEM0002"
},
{key:1,
value: "ITEM0001"
},
{key:3,
value: "ITEM0003"
}
];
function removeDuplicates(array){
var o = {};
array.forEach(function(item){
o[item.key] = item.value;
});
return o;
}
function get_data(){
console.log('get_data');
}
var sanitised = removeDuplicates(dataFromBackend);
var select = document.createElement('select');
select.id = "itemcode";
select.addEventListener('change', get_data);
Object.keys(sanitised).forEach(function(key){
var option = document.createElement('option');
option.value = key;
option.textContent = sanitised[key];
select.appendChild(option);
})
document.getElementById('container').appendChild(select);
i am using jquery instead of java script
<select id="itemcode">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
jquery
$('#itemcode:option').on("click",function(){
alert(saaas);
})
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.
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.
Is it possible to detect if no option was explicitly selected in a select box?
I have tried these methods but none of them works:
<select id="mySelect">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
Trial 1:
alert($('#select option:selected').length); // returns 1
Trial 2:
alert($('#select option[selected=selected]').length); // returns 1
Trial 3:
alert($('#select option:selected').attr('selected')); // returns 'selected'
Any ideas SO people?
Try This:
<select id="mySelect">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select><input type="button" id="btncheck" value="check"/>
Use this JS:
$('#btncheck').click(function(){
if ($("#mySelect ")[0].selectedIndex <= 0) {
alert("Not selected");
}
else
alert("Selected");
});
It will check if your dropdown was selected.
Try this fiddle: http://jsfiddle.net/aPYyt/
Hope it helps!
PS: You will have to make first value as default value.
This is how a normal select element works: the first option is selected if no other option has selected attribute set. The simplest workaround is to add an empty option as the first option, like this:
$(function() {
console.log($("#mySelect").val());
console.log($("#mySelect").get(0).selectedIndex);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect">
<option value="">-- select an item --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
then test one of these conditions:
$("#mySelect").val() === "";
$("#mySelect").get(0).selectedIndex === 0;
$("#mySelect option:selected").index() === 0;
A select box always has a value. If you don't manually change from the default value, you still have a value. For checking for explicit changes, as you say, you could monitor change:
$('#select').change(function() { $(this).data('changed', true); });
Your condition, then, would be:
if(!!$('#select').data('changed')) { ... }
The more common way of achieving something similar would be to insert a placeholder value at the top:
<option value="0">Please select one item</option>
... and test for
$('#select').val() == '0'
If you need to find out whether the select has been changed from its original value, i.e. the above test, but making sure that the user doesn't switch back to the default, you coul simply store the original value at page load:
$('#select').data('original-value', $('#select').val());
And check for
$('#select').val() != $('#select').data('original-value');
By default whatever option comes on index 0 is considered by browser as selected. The solution to problem would be inserting a dummy option at index 0 and before form submission you can validate it using something like
if($("#selectBox option").index("option:selected")>0)
$("#myForm").submit();
var $inputs_select_options = $('option:selected');
// remove empty(first option as default , value=="" ) options:
$inputs_select_options = $inputs_select_options.filter(function() {
return this.value.length; //check by length value
});