Get current selected option - javascript

<select id="sel">
<option id="1">aa</option>
<option id="2">bb</option>
<option id="3">cc</option>
</select>
$("#sel").change(function(){
alert($(this).children().attr('id'))
})
LIVE: http://jsfiddle.net/cxWVP/
How can i get current selected option ID? Now always show me id="1".

$('#sel').change(function(){
alert($(this).find('option:selected').attr('id'));
});
should work.

http://jsfiddle.net/cxWVP/1/
$("#sel").change(function(){
alert( this.options[this.selectedIndex].id );
})

<option> tags should have a value attribute. When one is selected, you get it's value using $("#sel").val().
<select id="sel">
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
</select>
$("#sel").change(function(){
alert($(this).val())
});
DEMO: http://jsfiddle.net/yPYL5/

http://jsfiddle.net/ugUYA/
To get the selected option inside a select element, you can use selectedIndex, then you can use the options array to get to the selected option object
$("#sel").change(function(){
alert( this.options[this.selectedIndex].id )
})

Try this
$("#sel").find('option:selected').attr('id');
Ideally you should use value attribute for option tags and just use val method to get the selected value from the dropdown element. $("#sel").val();

$(this).find('option:selected').attr('id')

Try this :
$('select:#idSelect').val()

Change the id attribute to value and then use .val().
<select id="sel">
<option value ="1">aa</option>
<option value ="2">bb</option>
<option value ="3">cc</option>
</select>
var selectedValue = $("#sel").val();

Will the jquery :selected filter work.
Something like this...
$("#sel:selected").each(function(){
alert($(this).attr('id'))
})

Related

How to get the 'name' property on 'option' tag

<select name="/static/images/legends/default.png" class="legend-icon">
<option class="legend-icon" name="/static/images/legends/icon1.png">option1</option>
<option class="legend-icon" name="/static/images/legends/icon2.png">option2</option>
<option class="legend-icon" name="/static/images/legends/icon3.png">option3</option>
</select>
When the value of the combobox changes I want the newly chosen option's 'name'. Is this possible to be done? If yes, how? I tried this:
$('select').change(function(e) {
alert(e.delegateTarget.name);
});
This alerts the 'name' of the 'select' tag. But I need the name of the 'option' tag. Any help?
You need to find the selected option and then find its name attribute value
$('select').change(function (e) {
alert($(this).find(':selected').attr('name'));
});
Demo: Fiddle
Here's one solution:
http://jsfiddle.net/HLYYB/
$('select').change(function(e) {
console.log($('option:selected', this).attr('name'));
});
$('select').change(function(e) {
console.log($(this).find('option:selected').attr('name'));
});
http://jsfiddle.net/xZf42/
Note: As #meagar mentioned in his comment to your question, name is not a standard attribute of option elements. Consider using custom attributes prefixed with data-:
<option class="legend-icon" data-name="/static/images/legends/icon1.png">
option1
</option>

setting the value of a select form with jquery

so apparently you have the following
<select>
<option value="0">One</option>
<option value="1">Two</option>
</select>
$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
but what if you have
<select>
<option value="0">1</option>
<option value="1">0</option>
</select>
And I want to set the value...of the form...how can I tell jquery to specifically use the value field or specifically the text in between the option tag...
​$('select').find('option[value="1"]')​​​​​​​​​​​​​​​​​.attr('selected', true );
Just select the option based on the value (with the attribute selector) and set the selected attribute like this:
var value = "1"; // Set the value that you want to select
$("select option[value=" + value + "]")​​.attr("selected","selected")​​;​
http://jsfiddle.net/VU9BC/
Just select the option based on the value (with the attribute selector) and set the selected attribute like this Simply no Headace :)
By Value
$( "select" ).change( displayVals );
https://jsfiddle.net/haroonmind/quemz47o/1/

jQuery : How to check if NO option was explicitly selected in a select box

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
});

How to select option in jQuery using text of option tag

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());
});

how to get the selected index of a drop down

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.

Categories