I have a normal dropdown which I want to get the currently selected index and put that in a variable. Jquery or javascript. Jquery perfered.
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
$("select[name='CCards'] option:selected") should do the trick
See jQuery documentation for more detail: http://api.jquery.com/selected-selector/
UPDATE:
if you need the index of the selected option, you need to use the .index() jquery method:
$("select[name='CCards'] option:selected").index()
This will get the index of the selected option on change:
$('select').change(function(){
console.log($('option:selected',this).index());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="CCards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
If you are actually looking for the index number (and not the value) of the selected option then it would be
document.forms[0].elements["CCards"].selectedIndex
/* You may need to change document.forms[0] to reference the correct form */
or using jQuery
$('select[name="CCards"]')[0].selectedIndex
the actual index is available as a property of the select element.
var sel = document.getElementById('CCards');
alert(sel.selectedIndex);
you can use the index to get to the selection option, where you can pull the text and value.
var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);
<select name="CCards" id="ccards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
<script type="text/javascript">
/** Jquery **/
var selectedValue = $('#ccards').val();
//** Regular Javascript **/
var selectedValue2 = document.getElementById('ccards').value;
</script>
You can also use :checked for <select> elements
e.g.,
document.querySelector('select option:checked')
document.querySelector('select option:checked').getAttribute('value')
You don't even have to get the index and then reference the element by its sibling index.
Related
I am trying to clear selected value on a button click using jQuery.
$("#cityCode")[0].selectedIndex = 0;
This is working fine for a single selector, but if I target multiple selectors like this
$("#cityCode, #townCode")[0].selectedIndex = 0;
It works only for first ID. Can anyone help me to write fix syntax?
To clear all selected options from dropdown on a button click.
As you're selecting multiple elements you need to reset the selectedIndex on all of them, not the 0th element. To do that you can use an each() loop:
$("#cityCode, #townCode").each((i, el) => el.selectedIndex = 0);
Alternatively, if the first option in both dropdowns has an empty value, eg. <option value="">Please select</option>, then you can use the val() method which will implicitly loop for you:
$("#cityCode, #townCode").val('');
Use jQuery's .prop() method:
Set the selected option to 0 index
This is considered bad practice since the defaultSelected might not necessarily be the option at index 0. Such depends on which option had originally the selected HTML attribute set (see the other example). This is only OK -ish if you don't use such attribute on your Option elements.
$("#cityCode, #townCode").prop("selectedIndex", 0);
<select id="cityCode">
<option>111</option>
<option selected>222</option>
<option>333</option>
</select>
<select id="townCode">
<option>aaa</option>
<option selected>bbb</option>
<option>ccc</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
In vanilla JavaScript:
document.querySelectorAll("#cityCode, #townCode").forEach(elSelect => {
elSelect.selectedIndex = 0;
});
Reset option to original defaultSelected index
Notice that the above sets specifically the index to 0 (first option element), which might not be the original defaultSelected.
To account for this use:
$("#cityCode").val("333"); // just to force emulate some dynamic change
$("#townCode").val("ccc");
$("#cityCode, #townCode").prop("selectedIndex", function() {
const idx = [...this.options].findIndex((opt) => opt.defaultSelected);
return idx < 0 ? 0 : idx;
});
<select id="cityCode">
<option>111</option>
<option selected>222</option>
<option>333</option>
</select>
<select id="townCode">
<option>aaa</option>
<option selected>bbb</option>
<option>ccc</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Reset form
If instead, you wish to reset the entire form use:
$("#someForm")[0].reset();
Don't use .val("")
as suggested in other answers... don't use .val(""). Here's why:
$("#cityCode, #townCode").val("");
<select id="cityCode">
<option>111</option>
<option selected>222</option>
<option>333</option>
</select>
<select id="townCode">
<option>aaa</option>
<option selected>bbb</option>
<option>ccc</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Try this:
$("#cityCode, #townCode").each(function(){
$(this).selectedIndex = 0;
});
I have a dropdown and I need to get the entire object using the value. I can get it using the text with contains but the same does not work by value. Here is my code. What am I doing wrong?
//var option = $("#car option:contains('Volvo')");
//alert(option.attr('value'));
var option = $("#car option:contains('value1')");
alert(option.attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="car">
<option value="value1">Volvo</option>
<option value="value2">Saab</option>
<option value="value3">Mercedes</option>
<option value="value4">Audi</option>
</select>
The commented portion works fine. I need to find a way to get the entire object using the value instead.
While :contains selector select elements that contain the specified text. You can use [attribute = "value"] .. I highly recommended to read about Selectors Here
//var option = $("#car option:contains('Volvo')");
//alert(option.attr('value'));
var option = $("#car option[value='value1']");
alert(option.attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="car">
<option value="value1">Volvo</option>
<option value="value2">Saab</option>
<option value="value3">Mercedes</option>
<option value="value4">Audi</option>
</select>
//var option = $("#car option:contains('Volvo')");
//alert(option.attr('value'));
var option = $("#car option[value=value1]");
alert(option.attr('value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="car">
<option value="value1">Volvo</option>
<option value="value2">Saab</option>
<option value="value3">Mercedes</option>
<option value="value4">Audi</option>
</select>
The issue is that jQuery :contains refer only to the text node of the element,not the content of an attribute.
you can use selector of an attribute in the following way:
var option = $("#car option[value=value1]");
alert(option.attr('value'));
var e = document.getElementById("car");
var selectedOption = e.options[e.selectedIndex].value;
alert(selectedOption);
First you target the selection list element with variable e, then you use the state of that element and assign it to selectedOption.
I'm a little bit confused about how to get an index of a selected option from a HTML <select> item.
On this page there are two methods described. However, both are always returning -1. Here is my jQuery code:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
alert($("#dropDownMenuKategorie option:selected").index());
alert($("select[name='dropDownMenuKategorie'] option:selected").index());
});
});
and in html
(...)
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
(...)
Why this behavior? Is there any chance that the select is not "ready" at the moment of assigning its change() method? Additionally, changing .index() to .val() is returning the right value, so that's what confuses me even more.
The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.
Just use the selectedIndex property of the DOM element:
alert($("#dropDownMenuKategorie")[0].selectedIndex);
Update:
Since version 1.6 jQuery has the prop method that can be used to read properties:
alert($("#dropDownMenuKategorie").prop('selectedIndex'));
Good way to solve this in Jquery manner
$("#dropDownMenuKategorie option:selected").index()
You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.
var savedIndex = $(selectElement).prop('selectedIndex');
This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:
$(selectElement).prop('selectedIndex', savedIndex);
I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.
var vOptionSelect = "#productcodeSelect1";
The index is returned with:
$(vOptionSelect).find(":selected").index();
try this
alert(document.getElementById("dropDownMenuKategorie").selectedIndex);
selectedIndex is a JavaScript Select Property. For jQuery you can use this code:
jQuery(document).ready(function($) {
$("#dropDownMenuKategorie").change(function() {
// I personally prefer using console.log(), but if you want you can still go with the alert().
console.log($(this).children('option:selected').index());
});
});
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
Actually just reiterating what has already been stated a little differently:
$("#dropDownMenuKategorie").change(function() {
var Selection = $("#dropDownMenuKategorie option:selected");
alert(Selection.index());
alert(Selection.val());
});
Assume You have jquery loaded. So
HTML :
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
JS:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
var selIndex = $(this).prop('selectedIndex');
var selVal = $("#dropDownMenuKategorie option:selected").val();
var selText = $("#dropDownMenuKategorie option:selected").text();
console.log(selIndex + selVal + selText );
});
});
This has probably been answered, but I am unable to find the answered question anywhere...
Assuming we have the following HTML...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dropdown Test</title>
</head>
<body>
<select name="myDropDownListName" id="myDropDownListID" class="dropdown">
<option selected="selected" value="0">Please select a value...</option>
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
</body>
</html>
What would the JQuery command look like to set 'My Custom value 2' to be the currently selected option in the dropdown list box, assuming I do not know the index 'value' value, and can only identify the item by the text 'My Custom Value 2'?
You can use jquery .filter():
$('#myDropDownListID option').filter(function() {
//you can use this.innerText too
return $(this).text() === 'My Custom Value 2';
}).prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="myDropDownListName" id="myDropDownListID" class="dropdown">
<option selected="selected" value="0">Please select a value...</option>
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
Simply like this :
$('select').val($("select option:contains('My custom Value 2')").val());
Another way... use the contains selector to search for a DOM elem by its content.
$('select>option:contains("My Custom Value 2")').prop('selected', true);
People like to say to use .val(), but as you noticed, it doesn't like to set by text, but by using the index, instead. So you should do a find to get that, then set by it. But even that is only part of the story. You should first deselect all other options, and set the attribute of the option you want as selected using the index that you find.
Btw, I hate the $('#myDropDownListID') syntax because it is useless in SharePoint because it auto-generates GUIDs and puts them after the IDs, forcing you to have to grab it with $('[id*=myDropDownListID]'), with the * indicating that it contains that value, so that is how I will set this up, except I'll leave out the * because it's unnecessary in this case. But this syntax is also very useful if you want to use $ instead of * to say it starts with that value, and you can use title or name instead of id, so it is incredibly versatile, and I wish more people used it.
$(document).ready(function() {
var yourText = "My Custom Value 2";
// Remove all 'selected' attributes from all options
$('select[id="myDropDownListID"] option').removeAttr('selected');
// Get the index for the value you want to set
var idx = $('select[id="myDropDownListID"] option').filter(function() {
return $(this).html() == yourText;
}).val();
// Set the dropdown value by index and set it as selected by text
var dropdownBox = $('select[id="myDropDownListID"]');
dropdownBox.val(idx);
dropdownBox.find('option[value="' + yourValue + '"]').attr('selected','selected'); // note that .val() doesn't do this
dropdownBox.click(); // may be useful and necessary for certain engines to cache the value appropriately
console.log(dropdownBox.html()); // should show you that the selected option is My Custom Value 2
console.log(dropdownBox.val()); // should give you the index 2
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="myDropDownListID">
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>
ddlListItems is ID of ListBox
if ($('#ddlListItems option:selected').text() == 'My Custom Value 2') {
var itemsByValue = $('#ddlListItems option:selected').text();
}
I'm trying to select a certain option in a select box, but it's not working:
var category = $(row + 'td:nth-child(4)').text();
$('#category_id', theCloned).load('/webadmin/video/get_categories',function(){
$('#category_id', theCloned).val(category);
});
There's no error thrown, but it doesn't change the select box. What am I doing wrong here?
Here is an example of the options loaded by the load() call:
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
The value of the category variable is "Fun" or "Capabilities", etc.
var $selectbox = $('#category_id', theCloned), // cache the element to avoid lookup overheads
category = $(row + 'td:nth-child(4)').text();
$selectbox.load('/webadmin/video/get_categories', function(){
$selectbox
.find('option')
.filter(function(){
return $(this).text() === category;
})
.prop('selected', true);
});
Update 1
Updated the code to adjust to the code you presented in your update. This will work. However if an option will contain a part of the string and not the full string it will still be part of the selected elements. E.g.
If the options will be
<option value="1">Capabilities</option>
<option value="2">Application Focus</option>
<option value="5">Fun</option>
<option value="6">Fun Time</option>
<option value="6">Funhouse</option>
And the category variable will have the value Fun, all three last options will be part of the selector.
Update 2
Changed the code to filter the options whose text fully matches the value of the category variable. Thus, you won't have to worry about the Update 1 above.
$('#id_of_select_box').val('your_value');
this will do
Try this
$('#category_id', theCloned).val($.trim(category));
At last i found a new solution Fiddle
<select>
<option value='1'>one</option>
<option value='2' >two</option>
<option value='3' >three</option>
</select>
Script
$("select").on("change",function(){
alert($("select option:selected").text());
});