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;
});
Related
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 );
});
});
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
});
I need help solving a simple requirement.
<select id="my-select1">
<option value="1">This is option 1 ({myop1}|OP)</option>
<option value="2" selected>This is option 2 ({myop1}|OQ)</option>
<option value="3">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="1">This is option 1 ({myop2}|PP)</option>
<option value="2">This is option 2 ({myop2}|PQ)</option>
<option value="3" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="1">This is option 1 ({myop3}|QP)</option>
<option value="2">This is option 2 ({myop3}|QQ)</option>
<option value="3" selected>This is option 3 ({myop3}|QR)</option>
</select>
See the HTML above, I want to recreate my array:
combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
INTO
combo = ["abc-OQ-PR", "def-PR"];
based on the selected options.
Another thing to note is that I cannot simply change the value of the options of the select box, meaning to say the HTML is somewhat as it is, if it would help, the only part i can restructure on that HTML is the text content between <option></option>
I'm not sure, but I'm already spending a couple of hrs just to solve this problem. Maybe due to my limited jQuery knowledge.
Please help. thanks
Get the selected values into an associative array:
var pattern = {};
var s = $('select option:selected').each(function(){
var m = /\((.*?)\|(.*)\)/.exec($(this).text());
pattern[m[1]] = m[2];
});
Then you can replace each place holder in each string in the array with the corresponding value:
combo = $.map(combo, function(e){
return e.replace(/\{.*?\}/g, function(m){
return pattern[m];
});
});
Demo: jsfiddle.net/C97ma/
Based on the information you provided I'm don't get it 100% I guess. But whatever you're trying to do, I guess jQuerys .map() and $.map() would help you here.
Like
var arr = $('select').find('option:selected').map(function(index, elem) {
return elem.textContent || elem.text;
}).get();
Demo: http://www.jsfiddle.net/4yUqL/78/
Within the callback you can modify/match the text in any way you want/need. In your case I could imagine you want to use a regular expression to match the selected strings and recreate those somehow.
I figure you're using javascript for combining those (it can be done with PHP also)..
You need references to your selects, e.g. :
<script type="text/javascript">
a=document.getElementById("myselect").options[1];
</script>
This will assign the 2nd option value from the 'myselect' select element to the variable 'a'
To begin with I would change the values in the select box like this:
<select id="my-select1">
<option value="OP">This is option 1 ({myop1}|OP)</option>
<option value="OQ" selected>This is option 2 ({myop1}|OQ)</option>
<option value="OR">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="PP">This is option 1 ({myop2}|PP)</option>
<option value="PQ">This is option 2 ({myop2}|PQ)</option>
<option value="PR" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="QP">This is option 1 ({myop3}|QP)</option>
<option value="QQ">This is option 2 ({myop3}|QQ)</option>
<option value="QR" selected>This is option 3 ({myop3}|QR)</option>
</select>
Now to update your array:
var comboDef = ["abc-{myop1}-{myop2}", "def-{myop2}"];
var combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
function updateArray() {
combo = comboDef;
for (i in combo)
{
combo[i] = combo[i].replace("{myop1}",document.getElementById("my-select1").value);
combo[i] = combo[i].replace("{myop2}",document.getElementById("my-select2").value);
combo[i] = combo[i].replace("{myop3}",document.getElementById("my-select3").value);
}
}
Of course, this could be done better with proper arrays (if you gave your select boxes the same name you could iterate through them using document.getElementsByName()). The basic idea is the replace though which I trust is what you're looking for.
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.