Adding additional data to select options using jQuery - javascript

Very simple question I hope.
I have the usual <select> box like this
<select id="select">
<option value="1">this</option>
<option value="2">that</option>
<option value="3">other</option>
</select>
I can get the selected value (by using $("#select").val()) and the selected item's display value (by using $("#select :selected").text().
But how can I store like an additional value in the <option> tag? I would like to be able to do something like <option value="3.1" value2="3.2">other</option> and get the value of the value2 attribute (which would be 3.2 in the example).

HTML Markup
<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>
Code
// JavaScript using jQuery
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
...
});
});
// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');
See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/
By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.

To me, it sounds like you want to create a new attribute? Do you want
<option value="2" value2="somethingElse">...
To do this, you can do
$(your selector).attr('value2', 'the value');
And then to retrieve it, you can use
$(your selector).attr('value2')
It's not going to be valid code, but I guess it does the job.

I made two examples from what I think your question might be:
http://jsfiddle.net/grdn4/
Check this out for storing additional values. It uses data attributes to store the other value:
http://jsfiddle.net/27qJP/1/

HTML
<Select id="SDistrict" class="form-control">
<option value="1" data-color="yellow" > Mango </option>
</select>
JS when initialized
$('#SDistrict').selectize({
create: false,
sortField: 'text',
onInitialize: function() {
var s = this;
this.revertSettings.$children.each(function() {
$.extend(s.options[this.value], $(this).data());
});
},
onChange: function(value) {
var option = this.options[value];
alert(option.text + ' color is ' + option.color);
}
});
You can access data attribute of option tag with option.[data-attribute]
JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/

HTML/JSP Markup:
<form:option
data-libelle="${compte.libelleCompte}"
data-raison="${compte.libelleSociale}" data-rib="${compte.numeroCompte}" <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>
JQUERY CODE:
Event: change
var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');
To have a element libelle.val() or libelle.text()

To store another value in select options:
$("#select").append('<option value="4">another</option>')

Related

When registering both onchange and onclick on a select, the click event is triggered twice

Goal: Have a select whose option have nested structure when user clicks on the select, but when user selects an option the option should be displayed "normally" (ie with no leading spaces).
Attempted solution using JS and Jquery: My JS is far from sophisticated so I apologize in advance :)
I attempted to use .on("change") and .on("click") to change the selected option value (by calling .trim() since I achieve the "nested" structure with ). I'm also storing the original value of the selected option because I want to revert the select menu to its original structure in case the user selects another option.
The problem: The function registered for .on("click") is called twice, thus the select value immediately resets itself to its original value.
I suspect there is a much, much easier solution using CSS. I will be happy to accept an answer that will suggest such solution.
JSFiddle: https://jsfiddle.net/dv6kky43/9/
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
<textarea id="output"/>
var orig;
var output = $("#output");
output.val("");
function onDeviceSelection(event){
output.val(output.val() + "\nonDeviceSelection");
var select = event.target;
orig = select.selectedOptions[0].text;
select.selectedOptions[0].text = select.selectedOptions[0].text.trim()
}
function resetDeviceSelectionText(event) {
output.val(output.val() + "\nresetDeviceSelectionText");
var select = event.target;
if (orig !== undefined){
select.selectedOptions[0].text = orig;
}
}
$("#select").on("change", onDeviceSelection);
$("#select").on("click", resetDeviceSelectionText);
If you are already using jQuery, why not utilize data function to store the original value. This way you will also be able to specify different nest levels.
(function($){
$(document).on('change', 'select', function(event) {
$(this).find('option').each(function(index, element){
var $option = $(element);
// Storing original value in html5 friendly custom attribute.
if(!$option.data('originalValue')) {
$option.data('originalValue', $option.text());
}
if($option.is(':selected')) {
$option.html($option.data('originalValue').trim());
} else {
$option.html($option.data('originalValue'));
}
})
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
Once caveat I see is, the selected option will appear trimmed on the list as well, if dropdown is opened after a previous selection has been made:
Will it still work for you?
Instead of keeping the state of the selected element i would simply go over all options and add the space if that option is not selected:
function onDeviceSelection(event){
// Update textarea
output.val(output.val() + "\nonDeviceSelection");
// Higlight the selected
const {options, selectedIndex} = event.target;
for(let i = 0; i < options.length; i++)
options[i].innerHTML = (i === selectedIndex ? "":" ") + options[i].text.trim();
}
$("#select").on("change", onDeviceSelection);
Note that you need to use innerHTML to set the whitespace...

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

make a select dependent with js

I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach

How to get the text attribute of a dropdown

I am wondering how I can retrieve the text of the selected item in a dropdown using JQuery. Currently the code I have retrieves the value and I actually need the text associated with that value.
This is my code:
var stockCode = $(this).closest('li').find('.stock_code').html();
var quantity = $(this).closest('li').find('.order_amount').val();
var growers = $(this).closest('li').find('.growers').val();
var sharequantity = $(this).closest('li').find('.share_amount').val();
This is HTML
<span class="bulk" style="">
<select name="CMP Member" id="CMP Member" class="growers">
<option value="0">Choose Grower to Share...</option>
<option value="10">xxxxx</option>
<option value="25">xxxxx</option>
<option value="4">xxxxxx</option>
<option value="6">xxxxxx</option>
</select>
I required the text at xxxxx...
Many thanks for any help. Also must point out I've got multiple dropdowns being generated dynamically so I would need to reference it by class.
Try this:
$('.growers option:selected').text()
Use val() for the option value attribute and text() for the text inside the option:
$(".growers option:selected").text();
You have to get it by using the :selected selector along with the .text() function
var growers = $(this).closest('li').find('.growers option:selcted').text();

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Categories

Resources