I am trying to set a default option in a select menu from the local storage, I am using a GUID as the value.
<script type="text/javascript">
$(document).ready(function () {
var guid = getParameterByName("dashId");
//$("#cboDashboards").val(guid); - Attempt #1
//$("#cboDashboards > option[value=" + guid + "]").prop("selected", true); - Attempt #2
//jQuery('#cboDashboards > option[value="' + guid + '"]').prop('selected', true) - Attempt #3
});
document.getElementById("cboDashboards").onchange = function () {
localStorage.dashboardGuid = this.value;
window.location.href = "/Home/Index?dashId=" + this.value;
};
</script>
The GUID that gets stored is the same as the GUID that I try to populate the combo box with, however, I have tried three different methods of trying to populate the combo box and none have worked. Any suggestions to why this isn't working as expected?
EDIT -
Would this method have any effect on it? It's called to populate the combo box with the values:
function populateDashboard(data) {
var options = $("#cboDashboards");
$.each(data, function () {
options.append($("<option />").val(this.DashboardGuid).text(this.Name));
});
}
I populated some test data -
<select id="cboDashboards">
<option value="0">Select dashboard</option>
<option value="1">Select dashboard 1</option>
<option value="2">Select dashboard 2</option>
<option value="3">Select dashboard 3</option>
#* <option value="0">Select dashboard</option>*#
</select>
and I did :
$("#cboDashboards").val('1'); // - Attempt #1
This worked, so I seem to be having a problem with the GUID value?
Try with jQuery using this code:
function populateDashboard(data) {
var options = $("#cboDashboards");
$.each(data, function () {
options.append($("<option />").val(this.DashboardGuid).text(this.Name));
});
var guid = getParameterByName("dashId");
//select element
$('#cboDashboards option[value='+ guid +']').attr('selected', 'selected');
}
I hope this help.
Related
I am working on product filters where user select from the select box according to his/her preference but I am not getting selected value by user in jQuery.
html code:
<select name="product_filter" id="product_filter">
<option value="price_low_first">Price : Low to High</option>
<option value="price_high_first">Price : High to Low</option>
<option value="latest">Latest</option>
<option value="popular">Most Popular</option>
</select>
jQuery code:
$(function () {
$("#product_filter").change(function () {
alert("hi")
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
});
});
Hi I believe that your code is perfect. Once please check jquery.min.js is included in your file. Please check if there are any console errors.Thank you.
I have a basic GET form in my project that is used to filter through posts created by users. When I submit the form the values from the multiple select input are appended to the url like so:
project.dev/?maps[]=1&maps[]=2&maps[]=3
As you can see, the values are passed to the url via three separate key value pairs... However, I would like to know how to append the values to the url in the following format:
project.dev/?maps=1,2,3
Thanks in advance.
Assuming you're trying to send an array, how about Array.prototype.join?
var arr = [1, 2, 3];
console.log(arr.join(','));
// result: 1,2,3
I found a solution to this and thought I'd share it in hopes to help others overcome the same problem in the future.
HTML
<select id="region" name="region" multiple>
<option value="1">Region 1</option>
<option value="2">Region 2</option>
<option value="3">Region 3</option>
</select>
<select id="maps" name="maps[]" multiple>
<option value="1">Map 1</option>
<option value="2">Map 2</option>
<option value="3">Map 3</option>
</select>
<button id="search">Search</button>
JavaScript
<script>
$(function() {
$("#search").click(function() {
var params = {};
var getSelect = ['region', 'maps'];
$.each(getSelect, function(index, value) {
var select = $('#' + value);
if (select.val() != '') {
var selected = select.val();
if (select.attr('multiple'))
selected = selected.join(',');
params[value] = selected;
}
});
if (!$.isEmptyObject(params)) {
var url = [location.protocol, '//', location.host, location.pathname].join('');
window.location.href = url + '?' + $.param(params);
}
});
});
</script>
I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value
having a bit of trouble here, any help would be greatly appreciated...
I am trying to hide and show a bunch of list items based on several classes assigned to them.
In my JS Fiddle Example I have several items with classes relating to their description.
I have managed to hide and show these, but complex selections are not possible...
example: If I wanted to only see fabrics that are "premium", "blue" and "linen".
Something like this (that works lol) is what I am after...
$('.sel_range').click(function() {
range = document.getElementById("range").value;
if ($('.fabric_option').hasClass(range)) {
$('.' + range).fadeIn('fast', function() {
!$('.fabric_option').hasClass(range).fadeOut("fast");
});
}
});
Something like this should work
var selects = $('#range, #fabric, #colour');
selects.on('change', function() {
var el = selects.map(function(i, item) {
return item.value.indexOf('all_') === 0 ? '' : '.' + item.value;
}).get().filter(function(x) {
return x.length;
}).join('');
$('#fabric_options li').show().not(s?s:'*').hide();
});
FIDDLE
It starts with showing all the list items, then joins the values together to create a clas selector, leaving out the class if all_something is selected etc. and then hides everything that doesn't match, and if nothing is selected excludes everything.
I think it can be solved like this:
var range, fabric, colour;
var updateShown = function() {
$('li').show()
if (range) {
$('li:not(.' + range + ')').hide();
}
if (fabric) {
$('li:not(.' + fabric + ')').hide();
}
if (colour) {
$('li:not(.' + colour + ')').hide();
}
}
// Range
$('#range').change(function() {
range = $(this).val();
updateShown();
});
// Fabric
$('#fabric').change(function() {
fabric = $(this).val();
updateShown();
});
// Colour
$('#colour').change(function() {
colour = $(this).val();
updateShown();
});
With value="" of each select first option
<select id="range">
<option class="sel_range" value="">All Ranges</option>
<option class="sel_range" value="luxury">Luxury</option>
<option class="sel_range" value="premium">Premium</option>
<option class="sel_range" value="base">Base</option>
</select>
<select id="fabric">
<option class="sel_fabric" value="">All Fabrics</option>
<option class="sel_fabric" value="leather">Leather</option>
<option class="sel_fabric" value="linen">Linen</option>
<option class="sel_fabric" value="cotton">Cotton</option>
</select>
<select id="colour">
<option class="sel_colour" value="">All Colours</option>
<option class="sel_colour" value="red">Red</option>
<option class="sel_colour" value="blue">Blue</option>
<option class="sel_colour" value="green">Green</option>
</select>
jsFiddle demo
what about this?
$('#range').on('change',function () {
range = $("#range").val();
$('li').each(function(){
if(!$(this).hasClass(range)){
$(this).hide();
}else{
$(this).show();
}
});
});
// just for range, rest in fiddle
http://jsfiddle.net/J3EZX/6/
If you're using jQuery, just string them together with a . and no space, e.g.:
$(".linen.red.base").text("Help! I'm being replaced!");
I need to select only 3 options from the multiple select. If user selects more than 3 options than the last selected element should be replaced by the new one clicked.
I have a example as follows:
<select multiple id='testbox'>
<option value='1'>First Option</option>
<option value='2'>Second Option</option>
<option value='3'>Third Option</option>
<option value='4'>Fourth Option</option>
<option value='5'>Fifth Option</option>
<option value='6'>Sixth Option</option>
<option value='7'>Seventh Option</option>
<option value='8'>Eighth Option</option>
<option value='9'>Ninth Option</option>
<option value='10'>Tenth Option</option>
</select>
When user selects
First option
Second option
Third option
Now he reaches max selection limit 3 .If he click on the another option like Tenth Option I need to remove Third option and get selected Tenth option
For that i tried this but no idea how I can achieve my goal
<script type="text/javascript">
google.load("jquery", "1");
$(document).ready(function() {
//alert("1111");
var last_valid_selection = null;
$('#testbox').change(function(event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
latest_value = $("option:selected:last",this).val()
alert(latest_value);
}
});
});
</script>
Please suggest some idea or solution.
This works quite nicely:
var lastSelected;
$("#testbox").change(function() {
var countSelected = $(this).find("option:selected").length;
if (countSelected > 3) {
$(this).find("option[value='" + lastSelected + "']").removeAttr("selected");
}
});
$("#testbox option").click(function() {
lastSelected = this.value;
});
I had to set a global variable lastSelected as well as an options click event to capture the actual last option clicked (this.value in the change event was giving me the top selected option, not the actual last option).
Demo: http://jsfiddle.net/JAysB/1/
Well, I don't like jQuery, so I've developed the same (fiddle), but in pure, vanilla, easy-to-read JavaScript:
document.getElementById('testbox').selopt=new Array();
document.getElementById('testbox').onchange=function(){
for(i=0; i<this.childNodes.length; i++)
if(this.childNodes[i].tagName!='OPTION')
continue;
else{
if(this.childNodes[i].selected &&
this.selopt.indexOf(this.childNodes[i])<0)
this.selopt.push(this.childNodes[i]);
}
if(this.selopt.length==4)
this.selopt.splice(2,1)[0].selected=false;
}
P. S. No global variables! :P
var lastOpt;
$('#testbox option').click(function () {
lastOpt = $(this).index();
});
$('#testbox').change(function () {
if ($('option:selected', this).length > 3) {
$(' option:eq(' + lastOpt + ')', this).removeAttr('selected');
}
});
JSFIDDLE