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>
Related
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.
I have a select and I want it's selected option to change but I can't make it happen for some reason. This is the code that I have.
$("#ID option[value=grpValue]").prop('selected', 'selected').change();
If instead of using "grpValue" I type in the value manually for example value "3" it does work. But I want it to use grpValue.
So this for example does work.
$("#ID option[value=3]").prop('selected', 'selected').change();
What am I doing wrong in the first line?
Would appreciate the help, thanks in advance.
EDIT: I've already tried using option[value='grpValue'], doesn't work.
$(document).ready(function(){
$("#sel option[value='c']").attr("selected",true);
$("#sel option[value='c']").prop("selected",true);
});
<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>
<body>
<form>
<select id="sel">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</form>
</body>
</html>
you can use any one from prop() or attr() method both of useful
Is grpValue a variable? If so
$("#ID option[value="+grpValue+"]").prop('selected', 'selected').change();
will make the attribute selector do the work.
BTW, I think
$obj.prop('selected', true);
is the correct expression for prop.
$('#id_of_select').val('value_of_option_here');
Edit: To explain why the above code works. The first part:
Is the jQuery we use the following method to select an element by it's id, we could also select an element by it's class by simply changing the '#' to a '.'.
$('#id_of_select')
The statement following it refers to the value attribute that is attached to every input, select, textarea and button. The value is the string that is passed through when a form is submitted. For inputs this is the typed text, for selects it's the value of the selected option.
When we click an option in a select field, what we are actually doing is grabbing the value of the option and setting it as the selects value also, selects know what value is selected via the value, it can then grab the option text associated with this value. The code below (with a parameter) will set the value of the select field, in the same way it would if you were to click the option.
Note .val must have a parameter otherwise you are just asking jQuery what the value of the selected field is. With a value will set, without a value will get.
.val('value_of_option_here');
Hope this is a little more useful than my original answer, I've tried to break it down as much as possible though if it's a little confusing let me know.
Working example :
$("#ID option[value='b']").prop('selected', 'selected').change();
// if value in variable just replace $("#ID option[value="+valueInVar+"]")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ID" >
<option value = "a">a</option>
<option value = "b">b</option>
<option value = "c">c</option>
</select>
I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery.
for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined.
Any insight into this problem would be much appreciated.
to get/set the actual selectedIndex property of the select element use:
$("#select-id").prop("selectedIndex");
$("#select-id").prop("selectedIndex",1);
The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.
Check the Id of the element and also check your markup validates at here at W3c.
Without a valid dom jQuery cannot work correctly with the selectors.
If the id's are correct and your dom validates then the following applies:
To Read Select Option Value
$('#selectId').val();
To Set Select Option Value
$('#selectId').val('newValue');
To Read Selected Text
$('#selectId>option:selected').text();
$('#myId').val() should do it, failing that I would try:
$('#myId option:selected').val()
When setting with JQM, don't forget to update the UI:
$('#selectId').val('newValue').selectmenu('refresh', true);
$("#myId").val() should work if myid is the select element id!
This would set the selected item: $("#myId").val('VALUE');
Suppose you have created a Drop Down list using SELECT tag like as follows,
<select id="Country">
Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..
var result= $("#Country option:selected").text();
it will work fine.
I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.
<option value="1" data-value="MyText">MyText</option>
var DisplayText = $(this).find("option:selected").attr("data-value");
$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding
<select id="myId">
<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>
Try this
$('#your_select_element_id').val('your_value').attr().add('selected');
How do I get all select elements that do not have an option selected using jQuery?
<select id="one">
<option value=""></option>
<option value="test"></option>
</select>
<select id="two">
<option value=""></option>
<option selected value="test"></option>
</select>
What would the jQuery selector be that would return just #one based on no selection?
Refer to https://stackoverflow.com/a/63588880/3499595 if your case is not similar to OP (default value is "")
$('select option:selected[value=""]').parent()
Selects all the :selected options of all the select elements
Checks if the selected option has a value of "", which in your case means no option is actually selected.
Returns the parent (which would be a select)
You can take advantage of jQuery's .parent() and .not() functions. See below:
// selector for all 'select' elements with any option below it
var all = $("select>option").parent(); // alternative $("select")
// selector for all 'select' element with a selected child
var selected = $("select>option[selected]").parent();
// the subtraction set "all - selected" achieved by `not`.
var unselected = all.not(selected);
Note that jQuery's parent takes care of removing duplicates from a set of parents of child elements.
JsFiddle here.
The accepted answer gives all select elements with a selected option whose value is empty(""), which does answer the question in regard to the OP's sample HTML, where options with empty values are given, but it doesn't really answer the title question.
There is a difference between selecting an option with an empty value, and not selecting any option at all.
To select all select elements with no option selected, use
$('select').not(':has(option:selected)')
If you have jquery library then try
$('select option').filter(function(i,d){return !d.hasAttribute("selected")});
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.