Get element of select value - javascript

I have a HTML select drop down that is populated from a JQuery get request. You can view that here https://codepen.io/anon/pen/xjVjra
I am trying to get the following example element of the selected value on each change.
<small class="text-muted">ETH</small>
I have tried the following but that would just bring back the name of the selected option, which is not what I am after.
$(document).ready(function () {
$('#dropdown').on('change', function() {
alert( $(this).val()
});
});
Is it possible to drill to the inner code of the selected option and retrieve that data.
Thanks

I don't see how the question fits with the CodePen, but you could try something like this:
$("#cryptos :selected").attr("data-subtext");

I don't see any <small> tags in the HTML, as their shouldn't be because only <option> and <optgroup> are valid elements in a <select>.
If you meant <option>, you can use the :selected pseudo-class to get the actual <option> element instead of just its value:
// in select onchange where this == select element
$(this).find(':selected'); // the option element
Also, note that your CodePen example doesn't actually have the dropdown named #dropdown, so just make sure you use the appropriate selector.

Related

How to get the text and value from a dropdown in Javascript

I have a very basic question. I want to select the SELECTED text and dropdown value from the dropdown and show in the alert box.
My attempt:
Dropdown
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
JS
$("#Select").change(function()
{
alert($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
alert($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
alert($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
Question 1: What $(this) signifies? If it's signifies selected element then it should show the text also when doing $(this).text(). BUT IT DOESN'T work as expected.
Question 2: If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Please guide me.
My JSFIDDLE Attempt
In your change event handler, $(this) is the <select> element.
The element represented by $(this) depends on the context where it is used.
It usually is the element which triggered an event (like here), or the element targeted by the iteration of an .each() loop, for example.
When an <option> is selected, the <select> take its selected option value as a value...
It doesn't do it for the text of the selected option.
So that is why the second alert() statement doesn't work.
The keyword this in your example represents the element on which the event triggered. This means the select element. .text() return all text included in the element, so it gives all elements. .val() returns the value of an input, in this case it will return the value of the select, but beware as it does not return more than one value if you set mutiple=true.
Since we now know that .text() returns the text, and this is the input that changed, we can deduct that you'd prefer using .val() to get the value as it may differ from the display text.
alert($(this).find("option:selected").val());
$(this) is used to make the this object a JQuery object which includes some extra functionality.
You can try this if you want to get the selected item value and text:
$(this).find(":selected").val(); // Gets the value of the selected option, if the value attribute in the option element is null it will give you the text
$(this).find(":selected").text(); // Gets the text of the selected option
hi the 'this' part is the raw DOM element from javascript $(this) makes it a jquery object, so you can use jquery. In this case it's the select.
If I need to select the value and text of the dropdown is above mentioned is the efficient way to go about it.
Yes it's fine.
jQuery get specific option tag text
Answer to question 1:
$(this) means that you pass this to the $ function. In other words, you create a jQuery object from the this object. In your context, this refers to the elements matching the #Select selector: your select element.
$(this).text() is working normally because internally it calls innerText on the select tag: which contains the DOM code of your select and innerText contains all the text (not HTML) of the children of the select.
Answer to question 2:
To retreive the label of the selected option: $("#Select option:selected").text()
To retreive the value of the selected option: $("#Select option:selected").val()
You can alter what you already have written by changing this:
alert($(this).val() + $(this).text());
to:
alert($(this).val() + $("option:selected", this).text());
And overall giving you the code you already have.
$("#Select").change(function()
{
alert($(this).val() + $("option:selected", this).text());
alert($("#Select option:selected").text());
});
$(this) is just selecting the identified object that you are choosing to use 'change' on which in this case is the select box.
$("#Select").change(function() binds the function defined after this point to the HTML element <select id="Select" name="Select">. Therefore within that function, $(this) refers to that Select element. The information within that select element is: <option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>. This is why $(this).text() will give you all the options; you're asking for all the text inside that element.
($this).val() gets you the value of the overall select element, which is the text of the currently selected option.
this refers to the context which was used to invoke the function.
When you change the select option, this refers to the whole select dropdown.
If you look below, when I print the value of $(this).val, it gives the function which returns the value of the selected option.
Whereas, when I print the value of $(this).text, it gives the function which gives the whole select dropdown inner text.
To answer your second question, I think $(this).val() is more efficient as by using $(this) will always refer to the context which invokes the function. Thus, you can create modular code using it, by separating the use of anonymous function into a named function and using it for other select dropdown in your site, if you want in the future.
$("#Select").change(function()
{
console.log($(this).val);
console.log($(this).text);
console.log($(this).val()); // IF THIS WORKS FINE THEN NEXT LINE CODE SHOULD WORK TOO
console.log($(this).text()); // WHY THIS SHOWS ALL THE DROPDOWN TEXTS
console.log($("#Select option:selected").text()); // THIS JUST WORKS FINE
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">
Select a draft:
<select id="Select" name="Select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>

How to get the currently selected option of a dom modified select box?

I'm using a fake select box in my script which means the original select box is hidden and for styling purposes a ul is showing up. Whenever the selected value of this list changes the orginal select box does too.
There is a change function for that. Within that function is following code:
var el = $(e.currentTarget) ;
$('#my_select_box').children().removeAttr('selected');
$('#my_select_box option[value="'+el.attr('data-value')+'"]').attr('selected','selected');
After that change I want to retrieve the new selected value of the original select box in another function.
But the normal selector only gets the original value, not the new:
$('#my_select_box option:selected').val() //returns the wrong value
So how to I get the new value in the function I need it?
I tried this function:
$("#my_select_box").bind("DOMSubtreeModified", function() {
console.log($(this).find('option:selected').val());
});
It returns the correct value but not where I need it. So how can I retrieve the correct select box value out of the domtree live?
Thanks in advance!
instead of .attr('selected','selected');, try .prop('selected', true);

Set focus on specific select box

I have multiple select boxes in the pages. I want to set focus on first element of specific select box. Here it shows how to set focus on select box. I need to say which one too. I tried below code but it didn't set the focus.
$('#thirdDropBox select:first').focus();
If you want the user to have focus on the first of multiple select's, you can use the following jQuery code:
If you have an id for the first select, you can directly access that element with the following:
$(document).ready(function () {
$('#idOfFirstSelect').focus();
});
However, if you don't have the id, the following code should work.
Demo: http://jsfiddle.net/biz79/1qo6mxnf/
$(document).ready(function () {
$('select').first().focus();
});
On a separate note, if you also want to have a default option selected, you can set that option to "selected" in the HTML:
<option value="saab" selected="selected">Saab</option>
The JQuery selector:
$('#thirdDropBox select:first')
will select the first "select" html element that is a descendant of an html-element that has an ID-attribute with the value "thirdDropBox".
For more information see: http://api.jquery.com/descendant-selector/
You probably need to remove the '#thirdDropBox"-part from your selector:
$('select:first')

How can I add only unique options in multiple select tags which are in same class?

I need to dynamically add options to the select tags. Those options I will be fetching it from a file. There can be many selects in the form. Now I need to check all the selects whichever is in the same class If it doesn't have the option which I fetched from the file Then I need to add that option to that particular select.
var name = $(this).attr('name');
$('.slct').each(function(){
if($('this option[value="'+name+'"]').length==0)
{
$('<option>').val(name).text(name).appendTo(this);
}
});
When I tried the above code, Options are getting duplicated. For example I have 3 select tags. In the first tag I have an option called option1 remaining two tags are empty. Then after the execution of this code. First select tag contains the option1 twice and the remaining two tags contain only once. Can Someone tell me how do I do it ? I am new to jquery.
You can use find() to check if option with specific value exists in the select this way:
if($(this).find('option[value="'+name+'"]').length==0)
{
$('<option>').val(name).text(name).appendTo(this);
}
FIDDLE DEMO:
http://jsfiddle.net/3Lkv638x/1/

jquery replicate values in to other area

IS there an easy way to replicate values in to other areas
i.e. if i have 2 or 3 select menus or other form fields.
say
<select id=first>
<option>1</option>
<option>2</option>
</select>
<select id=second>
<option>3</option>
<option>4</option>
</select>
<div id=firstvalue></div>
<div id=secondvalue></div>
If i want the divs html to automatically show the values of the select box, Would I have to do a piece of code for change on either component ?
Thanks
Lee
You want one code to work on both? Try this (example on jsFiddle)
$("select").change(function() // retrieve all `select` elements
{
// gets the corresponding `div`
$("div").eq($(this).index())
.html($(this).val()); // sets the html value of the `div` to
// the selected value on the `select` element
});
From jQuery docs:
Selectors
.change()
.eq()
.index()
.val()
If you want the divs to automatically show the selected value of any selectbox you can use the following jQuery:
$('#first').change(function(){
/* target the first selectbox with id #first and bind a change event to it */
$('#firstvalue').html($(this).val());
/* set the html of the div with id #firstvalue to the selected option*/
});
/* the same for the second selectbox */
$('#second').change(function(){
$('#secondvalue').html($(this).val());
});
I would recommend changing your HTML though, so the selectboxes that are being handled have the same class and store their target within a data attribute. Like so:
HTML
<select class="show_val" data-target="#value_1">
<option>1</option>
<option>2</option>
</select>
<div id="value_1"></div>
jQuery
$('.show_val').change(function(){
$($(this).data('target')).html($(this).val());
}
This way you can use the same jQuery event for all selectboxes.
You'd use the change event on the select box via the change or bind functions, and in the event handler you'd call the html or text function to set the text on the relevant div, getting the value of the selected option via val (your option elements don't have value attributes, so val will grab their text instead). In both cases, you look up the elements via the $ (or jQuery) function passing in a CSS selector (e.g., $("#first")) for the first select box.
You could do something like this so you wouldn't have to write code for each select/div:
$('select').change(function() {
$('div[id^="' + this.id + '"]').text($(this).val());
});
JSFiddle Example
You could also check out knockout.js and implement the MVVM (Model-View-View-Model) pattern, if you're using a JavaScript backing object that is bound to the view/page.

Categories