Get select element by selected value - javascript

I'm looking for a way to get a select element using it's selected value.
It's easy for options : $('option[value="lol"]');
But it's not working with $('select[value="lol"]');
Is it possible to do this with a simple selector ?

You could use a filter?
$("select").filter(function() {
return $(this).val() === "lol";
});
jsFiddle Example
This is assuming you want all <select> elements where the lol option is actually selected. If you just wanted to check to see if the select contains the lol option, selected or not, you can use parent:
$('option[value="lol"]').parent();
jsFiddle Example

You could use something like this in jQuery:
var lol = getSelect(1);
lol.css({
"color": "red"
});
function getSelect(i) {
var option = $('select option[value="' + i + '"]');
return option.parent('select');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>

Related

Remove and add values from dropdown using javascript/jQuery

I am trying to achieve the following thing in my code but it is getting complicated.
I have 'n' dropdowns with or without duplicate values in it.
for simplicity lets assume following scenario:
dropdown1:
<select>
<option>100</option>
<option>200</option>
<option>102</option>
</select>
dropdown 2:
<select>
<option>100</option>
<option>200</option>
<option>201</option>
</select>
dropdown3 :
<select>
<option>100</option>
<option>300</option>
<option>301</option>
</select>
case1:
if user select value 100 from dropdown 1 then 100 should be removed from all the dropdowns.and when user change dropdown 1 value from 100 to 200 then 100 should be added back to all the dropdowns and 200 should be removed from all the dropdowns.
removing seems easy but adding back values is little difficult.
how can I maintain a list or some other data structure to remember which value to add and where incase of multiple value change? is there any advance jquery feature or generic javacript logic i can use ?
If it is sufficient to just disable the option instead of actually removing it, the following could work for you. You might want to adapt the handling of the selects when initially loading the site.
$('select option[value="' + $('select').eq(0).val() + '"]').not(':eq(0)').prop('disabled', true);
$('select').on('change', function() {
var val = $(this).val();
$('select option').prop('disabled', false);
$('select option[value="' + val + '"]').not($(this)).prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='102'>102</option>
</select>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='201'>201</option>
</select>
<select>
<option value='100'>100</option>
<option value='300'>300</option>
<option value='301'>301</option>
</select>
It would be better to set display to none instead. Hence, you will avoid the complications of adding or removing in the appropriate order.
So, you can easily return them visible.
$( "option" ).each(function( index ) {
$(this).css("display", "");
});
$("#drop").change(function () {
var selected_value=$(this).val();
var dropdown=$(select);
for(i=0;i<dropdown.length;i++){
$("dropdown[i] option[value=selected_value]").remove();
}
});
Set id of first dropdown="drop"
Here select the value and define it S a variable loop through dropdown with in page remove option when value=selected_value

Getting value from select drop-down [duplicate]

Usually I use $("#id").val() to return the value of the selected option, but this time it doesn't work.
The selected tag has the id aioConceptName
html code
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
For dropdown options you probably want something like this:
For selected text
var conceptName = $('#aioConceptName').find(":selected").text();
For selected value
var conceptName = $('#aioConceptName').find(":selected").val();
The reason val() doesn't do the trick is because clicking an option doesn't change the value of the dropdown--it just adds the :selected property to the selected option which is a child of the dropdown.
Set the values for each of the options
<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
<option value="0">choose io</option>
<option value="1">roma</option>
<option value="2">totti</option>
</select>
$('#aioConceptName').val() didn't work because .val() returns the value attribute. To have it work properly, the value attributes must be set on each <option>.
Now you can call $('#aioConceptName').val() instead of all this :selected voodoo being suggested by others.
I stumbled across this question and developed a more concise version of Elliot BOnneville's answer:
var conceptName = $('#aioConceptName :selected').text();
or generically:
$('#id :pseudoclass')
This saves you an extra jQuery call, selects everything in one shot, and is more clear (my opinion).
Try this for value...
$("select#id_of_select_element option").filter(":selected").val();
or this for text...
$("select#id_of_select_element option").filter(":selected").text();
If you are in event context, in jQuery, you can retrieve the selected option element using :
$(this).find('option:selected') like this :
$('dropdown_selector').change(function() {
//Use $option (with the "$") to see that the variable is a jQuery object
var $option = $(this).find('option:selected');
//Added with the EDIT
var value = $option.val();//to get content of "value" attrib
var text = $option.text();//to get <option>Text</option> content
});
Edit
As mentioned by PossessWithin, My answer just answer to the question : How to select selected "Option".
Next, to get the option value, use option.val().
Have you considered using plain old javascript?
var box = document.getElementById('aioConceptName');
conceptName = box.options[box.selectedIndex].text;
See also Getting an option text/value with JavaScript
$('#aioConceptName option:selected').val();
For good practice you need to use val() to get value of selected options not text().
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option value="choose">choose io</option>
</select>
You can use
$("#aioConceptName").find(':selected').val();
Or
$("#aioConceptName :selected").val();
Reading the value (not the text) of a select:
var status = $("#Status").val();
var status = $("#Status")[0].value;
var status = $('#Status option:selected').val();
How to disable a select?
in both variants, value can be changed using:
A
User can not interact with the dropdown. And he doesn't know what other options might exists.
$('#Status').prop('disabled', true);
B
User can see the options in the dropdown but all of them are disabled:
$('#Status option').attr('disabled', true);
In this case, $("#Status").val() will only work for jQuery versions smaller than 1.9.0. All other variants will work.
How to update a disabled select?
From code behind you can still update the value in your select. It is disabled only for users:
$("#Status").val(2);
In some cases you might need to fire events:
$("#Status").val(2).change();
With JQuery:
If you want to get the selected option text, you can use $(select element).text().
var text = $('#aioConceptName option:selected').text();
If you want to get selected option value, you can use $(select element).val().
var val = $('#aioConceptName option:selected').val();
Make sure to set value attribute in <option> tag, like:
<select id="aioConceptName">
<option value="">choose io</option>
<option value="roma(value)">roma(text)</option>
<option value="totti(value)">totti(text)</option>
</select>
With this HTML code sample, assuming last option is selected:
var text will give you totti(text)
var val will give you totti(value)
$(document).on('change','#aioConceptName' ,function(){
var val = $('#aioConceptName option:selected').val();
var text = $('#aioConceptName option:selected').text();
$('.result').text("Select Value = " + val);
$('.result').append("<br>Select Text = " + text);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="aioConceptName">
<option value="io(value)">choose io</option>
<option value="roma(value)">roma(text)</option>
<option value="totti(value)">totti(text)</option>
</select>
<p class="result"></p>
you should use this syntax:
var value = $('#Id :selected').val();
So try this Code:
var values = $('#aioConceptName :selected').val();
you can test in Fiddle: http://jsfiddle.net/PJT6r/9/
see about this answer in this post
to find correct selections with jQuery consider multiple selections can be available in html trees and confuse your expected output.
(:selected).val() or (:selected).text() will not work correct on multiple select options. So we keep an array of all selections first like .map() could do and then return the desired argument or text.
The following example illustrates those problems and offers a better approach
<select id="form-s" multiple="multiple">
<option selected>city1</option>
<option selected value="c2">city2</option>
<option value="c3">city3</option>
</select>
<select id="aioConceptName">
<option value="s1" selected >choose io</option>
<option value="s2">roma </option>
<option value="s3">totti</option>
</select>
<select id="test">
<option value="s4">paloma</option>
<option value="s5" selected >foo</option>
<option value="s6">bar</option>
</select>
<script>
$('select').change(function() {
var a=$(':selected').text(); // "city1city2choose iofoo"
var b=$(':selected').val(); // "city1" - selects just first query !
//but..
var c=$(':selected').map(function(){ // ["city1","city2","choose io","foo"]
return $(this).text();
});
var d=$(':selected').map(function(){ // ["city1","c2","s1","s5"]
return $(this).val();
});
console.log(a,b,c,d);
});
</script>
see the different bug prone output in variant a, b compared to correctly working c & d that keep all selections in an array and then return what you look for.
Just this should work:
var conceptName = $('#aioConceptName').val();
$(function() {
$('#aioConceptName').on('change', function(event) {
console.log(event.type + " event with:", $(this).val());
$(this).prev('input').val($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
Using jQuery, just add a change event and get selected value or text within that handler.
If you need selected text, please use this code:
$("#aioConceptName").change(function () {
alert($("#aioConceptName :selected").text())
});
Or if you need selected value, please use this code:
$("#aioConceptName").change(function () {
alert($("#aioConceptName :selected").attr('value'))
});
For anyone who found out that best answer don't work.
Try to use:
$( "#aioConceptName option:selected" ).attr("value");
Works for me in recent projects so it is worth to look on it.
Use the jQuery.val() function for select elements, too:
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of select elements, it
returns null when no option is selected and an array containing the
value of each selected option when there is at least one and it is
possible to select more because the multiple attribute is present.
$(function() {
$("#aioConceptName").on("change", function() {
$("#debug").text($("#aioConceptName").val());
}).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
<div id="debug"></div>
Straight forward and pretty easy:
Your dropdown
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
Jquery code to get the selected value
$('#aioConceptName').change(function() {
var $option = $(this).find('option:selected');
//Added with the EDIT
var value = $option.val(); //returns the value of the selected option.
var text = $option.text(); //returns the text of the selected option.
});
For get value of tag selected:
$('#id_Of_Parent_Selected_Tag').find(":selected").val();
And if you want to get text use this code:
$('#id_Of_Parent_Selected_Tag').find(":selected").text();
For Example:
<div id="i_am_parent_of_select_tag">
<select>
<option value="1">CR7</option>
<option value="2">MESSI</option>
</select>
</div>
<script>
$('#i_am_parent_of_select_tag').find(":selected").val();//OUTPUT:1 OR 2
$('#i_am_parent_of_select_tag').find(":selected").text();//OUTPUT:CR7 OR MESSI
</script>
You can try to debug it this way:
console.log($('#aioConceptName option:selected').val())
I hope this also helps to understand better and helps
try this below,
$('select[id="aioConceptName[]"] option:selected').each(function(key,value){
options2[$(this).val()] = $(this).text();
console.log(JSON.stringify(options2));
});
to more details please
http://www.drtuts.com/get-value-multi-select-dropdown-without-value-attribute-using-jquery/
If you want to grab the 'value' attribute instead of the text node, this will work for you:
var conceptName = $('#aioConceptName').find(":selected").attr('value');
Here is the simple solution for this issue.
$("select#aioConceptName").change(function () {
var selectedaioConceptName = $('#aioConceptName').find(":selected").val();;
console.log(selectedaioConceptName);
});
try to this one
$(document).ready(function() {
$("#name option").filter(function() {
return $(this).val() == $("#firstname").val();
}).attr('selected', true);
$("#name").live("change", function() {
$("#firstname").val($(this).find("option:selected").attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name">
<option value="">Please select...</option>
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>
<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">
$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);
Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.
You can use $("#drpList").val();
to fetch a select with same class= name you could do this, to check if a select option is selected.
var bOK = true;
$('.optKategorien').each(function(index,el){
if($(el).find(":selected").text() == "") {
bOK = false;
}
});
I had the same issue and I figured out why it was not working on my case
The html page was divided into different html fragments and I found that I have another input field that carries the same Id of the select, which caused the val() to be always empty
I hope this saves the day for anyone who have similar issue.
Try
aioConceptName.selectedOptions[0].value
let val = aioConceptName.selectedOptions[0].value
console.log('selected value:',val);
<label>Name</label>
<input type="text" name="name" />
<select id="aioConceptName">
<option>choose io</option>
<option>roma</option>
<option>totti</option>
</select>
There is only one correct way to find selected option - by option value attribute. So take the simple code:
//find selected option
$select = $("#mySelect");
$selectedOption = $select.find( "option[value=" + $select.val() + "]" );
//get selected option text
console.log( $selectedOption.text() );
So if you have list like this:
<select id="#mySelect" >
<option value="value1" >First option</option>
<option value="value2" >Second option</option>
<option value="value3" selected >Third option</option>
</select>
If you use selected attribute for option, then find(":selected") will give incorrect result because selected attribute will stay at option forever, even user selects another option.
Even if user will selects first or second option, the result of $("select option:selected") will give two elements! So $("select :selected").text() will give a result like "First option Third option"
So use value attribute selector and don't forget to set value attribute for all options!
You many try this:
var ioConceptName = $('#ioConceptName option:selected').text();

How you can I put selected = "selected" dynamic?Jquery

I have this sample:
link
CODE HTML:
<select name="card_type" id="card_type" class="card-sel com-c select-full">
<option value="visa">Visa</option>
<option value="mastercard">Mastercard</option>
<option value="discovery">Discovery</option>
<option value="maestro">Maestro</option>
</select>
CODE JS:
$( document ).ready(function() {
var stateSelectValue = "Mastercard"; //this value in my site returns a dynamic type of card
console.log("primul log" + stateSelectValue);
if(stateSelectValue)
{
console.log("al doilea log" + stateSelectValue); $("#card_type").val(stateSelectValue).attr("selected","selected").trigger("change");
console.log("al treilea log" + stateSelectValue);
}
$( ".com-c" ).change(function() {
var data= $(this).val();
console.log(data);
});
});
Perhaps the example understand what they want to do.
Basically when they are receiving a value in the variable stateSelectValue to look if there is value in that list and make selected.
For example IF:
var stateSelectValue = "Mastercard";
then
<option value="mastercard" selected="selected">Mastercard</option>
and so on...
Can you help me to solve this problem please?
Thanks in advance!
First as I have already commented, you do not need to set attribute selected and trigger change function.
$("#card_type").val(stateSelectValue)
This should be enough.
Second, if you do this change, still it will not work. W
Why?:
Variable value:
var stateSelectValue = "Mastercard";
is not equal to value of option
<option value="mastercard">Mastercard</option>
Updated Codepen
You were all good just one typo mistake, your selected value was in capital i.e "Mastercard" where as in option value it was "mastercard". But in simple way doing below was enough without trigger change event.
var stateSelectValue = "mastercard";
$("#card_type").val(stateSelectValue)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select name="card_type" id="card_type" class="card-sel com-c select-full">
<option value="visa">Visa</option>
<option value="mastercard">Mastercard</option>
<option value="discovery">Discovery</option>
<option value="maestro">Maestro</option>
</select>
This question already asked some . please refers the below link:
JQuery setting the selected attribute on a select list
$(document).ready(function () {
$('#card_type').val("mastercard"); // Select by value
text1 = "Maestro";
$("#card_type option:contains(" + text1 + ")").attr('selected', 'selected'); // select by text
});

jQuery - Set the selected option of a select box using value or text with options nested in optgroups

So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.

Showing and hiding <option> with jquery

I have three selects (html drop down lists), all contain the exact same values (except the ids of selects are different).
Now I want to do this:
When a user selects some option in the first select the same option is hidden in the other two. This rule applies to other two selects as well.
If the option in the second select is changed again then the previously selected option must reappear in the other selects.
I hope I was clear. I know this should probably be solved with javascript but I don't have enough knowledge of it to write an elegant solution (mine would probably be very long). Can you help me with the this?
$('#selectboxid').hide();
is the simplest way
http://api.jquery.com/hide/
try toggle it it matches your requirement
http://api.jquery.com/toggle/
you can call these onchange of the select box
if you want to hide individual options
use .addClass and add class to that option to hide it
http://api.jquery.com/addClass/
Little late the party, but here's a full working solution:
HTML:
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
JavaScript:
$(document).ready(function() {
$("select").change(function() {
var $this = $(this);
var selected = this.options[this.selectedIndex].value;
var index = $this.index();
$("select").each(function() {
var $this2 = $(this);
if($this2.index() != index) {
$(this.options).show();
var $op = $this2.children("option:[value='" + selected + "']");
$op.hide();
if($this2.val() == selected) {
if($op.index() + 1 == $ops.length) {
$this2.val($ops.eq(0).val());
}
else {
$this2.val($ops.eq($op.index() + 1).val());
}
}
}
});
});
});
Also demonstrated here: http://jsfiddle.net/thomas4g/u2sbd/21/

Categories

Resources