Find index of selected menu option using jquery - javascript

I have a select menu. I wish to obtain the index of the currently selected option. Upon initial page load, it would be zero unless selected="selected" is included in the HTML. If later it was changed, the index would indicate the currently selected option. The following works on my current browser, but I would like confirmation whether this is the best cross-browser solution.
var i=$('#mySelectID').prop("selectedIndex");
Note. While I show $('#mySelectID'), my example actually loops over several elements so it is really $(this), but I don't think that makes any difference.

You may also use index() method:
var i = $("#mySelectID :selected").index();
This is cross browser and gives a result on page load and if you have no options selected.
DEMO: http://jsfiddle.net/mZ9Dc/

var selectedIndex = $('#mySelectID :selected').index();

you can also use
var i=$('#mySelectID :selected').val(); //if you have given the values
or
var i=$('#mySelectID :selected').text(); //if you have used the text

Related

How to get values of 2 sides of jquery multiselect2side

Here's the jsfiddle for the code http://jsfiddle.net/VFskn/2/
The jquery multiselect2side has 2 parts for the list say the Available and Selected
a.To get the values of Selected portion of the I used the following code:
var multipleValues = $("#columnList").val() || [];
b. To get all values of the list I can use:
$('#columnList option').each(function() {
columns.push( $(this).attr('value') );
});
My Question is how I can obtain the Available portion of the list
If I understand your question right, you want to get the value of every option that is in the select under Available?
In the given example this select has the id "columnListms2side__sx", so that you can get the values of its options with
var multipleValues = [];
$("#columnListms2side__sx option").each(function()
{
multipleValues.push($(this).val())
});
here's the updated fiddle: http://jsfiddle.net/VFskn/3/
!important notes though: its not a good idea to mess with it, other then the functions provided by the plugin.
And I'm not sure how safe it is too assume that this select will allways get this id (e.g. if you have multiple of them in one page). It might be smarter to, build a more generic select. (the plugin seems to create a div container after the select it replaces, you want to get the first select in there)
EDIT:
this would be more generic, but less efficient:
$("#columnList").next().find("select").filter(":first").children().each(function(){...}
updated fiddle: http://jsfiddle.net/VFskn/4/

Use jQuery to set select box value to first option

I am dynamically populating a select box with options. When I do this, I want the value of the select box to be the value of the first option (a 'default option', if you like). Sounds really simple, but I just can't get it to work.
var myElement = $('select[name="myName"]');
.... tried the following three variations
// myElement.find('option').first().prop('selected', 'selected');
// myElement.val(myElement.find('options').first().val());
myElement.prop('selectedIndex', 0);
...but the following line gives a blank alert
alert(myElement.val());
Where am I going wrong?
options should be option
myElement.find('option:eq(0)').prop('selected', true);
You can use the eq selector on the option to select the first option.
If you know the value of the first option. Then you could simply do
myElemeent.val('first value') // Which selects the option by default
The 2nd case you tried should work, unless you are not calling at the right point . i.e; waiting for the ajax response to be completed.
Try calling that inside the done or the success (deprecated) handler
You almost got it, drop the 's' in 'options':
myElement.val(myElement.find('option').first().val());
Working jsFiddle
You could also use next code:
myElement[0].selectedIndex = 0;
This get's the Dom element (not jQuery object), works with vanilla Javascript and uses it to set the first option as the selected one based on it's index.
If you want to be sure that your option has a value and is not a placeholder you can do:
$('select option').filter( function (index, option) {
return option.attributes.value
}).val()
That way you'll check if the HTML node has attribute value and is not empty.

Change option value based on it's current value in jQuery

I have the following HTML:
<select class="file_image_type" name="file_image_type">
<option>Gallery</option>
<option>Feature</option>
<option>Thumbnail</option>
</select>
This is generated dynamically and is repeated for each item. Since there can only be one Feature image, I want to reset the option value of any labeled as "Feature" whenever a new image is selected as being a "Feature".
I've tried this jQuery but it doesn't seem to be responding:
current.find(".file_image_type option[value='Feature']").val("Gallery");
I'm able to set the image as Feature just fine using this:
current.find(".file_image_type").val("Feature");
"Gallery" is not the val(), it's the text().
People, people, you do not need to select the options directly in jQuery. I can't believe how many times I see this mistake.
$('.file_image_type').change(function() {
$('.file_image_type').not(this).each(function() {
var $this = $(this);
if ($this.val() === 'Feature') {
$this.val('Gallery');
}
});
});​

How do you scroll a select box to a specific point (using javascript or jQuery)?

I want to make the selected option appear in the middle of a drop-down. When I first load the page it appears at the bottom of the drop-down, but if I scroll past it and exit it remembers that when I open it again. I want it to make it appear in the middle by default.
At first I thought I could just use javascript to select an option past the one I want, then set it back to the correct option. I've played with scrollTop and scrollTo, but none of them seem to give me what I need. I've been testing it in Chrome, but it also needs to work in Firefox and IE. Any ideas?
Edit: I tried the scrollTo plugin but it doesn't seem to work for drop-downs. Take a look at these code snippets
From HTML:
<select id="test">
<option>1</option>
<option>2</option>
// ........
<option selected="selected">21</option>
<option>22</option>
// ........
<option>40</option>
</select>
From Javascript:
$(function() {
alert( $('#test option:selected').next().text() ); // alerts 22
$().scrollTo('#test'); // scrolls the screen to the drop-down
$('#test').scrollTo( $('#test option:selected').next() ); //does nothing
});
Use this jQuery plugin: http://plugins.jquery.com/project/ScrollTo
Documentation
Demo 1 or Demo 2
Edit -
Final Solution:
Because a drop-down list is brower-handled and can't be manipulated very well, you have to recreate the behavior of a drop-down list yourself. Look at the comments for more information.
What worked for me (in Chrome and Firefox):
<select onclick="centerSelectedOption(this)">
...
</select>
<script type="text/javascript">
function centerSelectedOption(selectBox) {
var selectedIndex = selectBox.selectedIndex;
var optionCount = selectBox.options.length
/* browser shows 20 options at a time (as long as list is long enough)
hence a center position of 10 would be fine
we can achieve this by briefly selecting the (selectedIndex+10)th option
and then back to the actual selectedIndex */
if (optionCount > 20) {
var upperIndex = Math.min(optionCount, selectedIndex + 10);
selectBox.selectedIndex = upperIndex; // hereby the browser scrolls the options list so that upperIndex is at the end
// if the options list was already scrolled down and an option higher up is selected, we have to scroll up again
var lowerIndex = Math.max(0, selectedIndex - 9);
selectBox.selectedIndex = lowerIndex; // hereby the browser scrolls the options list so that lowerIndex is at the top
// finally go back to the actually selected option
selectBox.selectedIndex = selectedIndex;
}
}
</script>
$(".MyDDL").val('2');
[jQuery.val] checks, or selects, all
the radio buttons, checkboxes, and
select options that match the set of
values.
I ran into this problem... my solution doesn't really use jquery (although the page itself does...) I thought this was more appropriate for what I was doing; and easier to implement than jquery. The problem I was having was properly making an HTML form update after javascript was used to get _GET params to pass off to ajax ... after the user hit 'submit' they would lose all of their selections.
function getURLParameter(param_name) {
// get the _get parameter
var check = decodeURI((RegExp(param_name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
// get the form in the document (by id/name)
if(typeof document.myForm[param_name] !== 'undefined'){
var form_param = document.myForm[param_name];
for(key2 in form_param.options)
if(form_param.options[key2].value == check){
// change index
form_param.selectedIndex = form_param.options[key2].index;
return check;
}
}
// Return a 'null' string value if get param isn't there
return check;
}

Javascript - Remember Selected Option

I have a webpage thats created by javascript injections and one of my pages has a dropdown shown below:
html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value); display(document.getElementById(\"searchQuery\").value);return false;'>\n";
html +="<option></option>\n";
html +="<option value='4'>Smallest First</option>\n";
html +="<option value='5'>Largest First</option>\n";
html +="<option value='6'>A-Z</option>\n";
html +="<option value='7'>Z-A</option>\n";
html +="</select>";
The dropdown filters the information displayed on the page by passing the selected option to a switch function and another function reloads this information. However, when the javascript page loads again, it starts off with the blank option.
Does anyone know of a good way to remember the last sort selected? For example, if I sort with "Smallest First" and then the page refreshes, the box will show "Smallest First" as apposed to the blank. I know there is an "option selected" attribute, but I need it to be dynamic. I feel like it is something trivial, yet I can't seem to put my finger on it.
Thanks in advance!
Here's an article on Cookies in JavaScript which contains an explanation of how they work, along with functions to read, write and delete cookies.
Using those functions you'd get the selected value and write the cookie to save the value like this:
var select = document.getElementById("Sort");
var selectedItem = select.options[select.selectedIndex].value;
createCookie("selectedItem",selectedItem);
then read the cookie to retrieve the value and select the option in the select box, like this:
var selectedItem = readCookie("selectedItem");
var select = document.getElementById("Sort");
select.value = selectedItem;
You need to use cookies. or some session variables on the server side to save the values that were selected.
I use this jQuery cookie plugin

Categories

Resources