Determining selected option using jQuery after using get() to retrieve the select - javascript

I have used get() to retrieve the first select drop down on the page like so:
styleSelect = jQuery('select').get(0);
And I can do normal things like
jQuery(styleSelect).remove();
To remove the select, but I'm having trouble finding the correct syntax to get the currently selected option's text. I've tried:
jQuery(styleSelect, ':selected').text();
and several variations of this, I think I'm just missing something dumb here.

jQuery('select').val()
should return the value of the currently selected element.
although, this does return the value. It is rare to return the text.
you could do it with something like the following:
jQuery('#test').change(function() {
//get text(), change to .val() to get value
var value = jQuery(':selected', this).text();
//insert value
jQuery('h2 span').html(value);
});
http://jsfiddle.net/pCsF9/
accompying html
<select name="test" id="test">
<option value="AA">AA</option>
<option value="MA">MA</option>
<option value="LA">LA</option>
<option value="GO">TEST</option>
</select>
<h2>selected:<span></span> </h2>
NOTE change .text() to .val() and select the last option to see the difference between selecting the value and text. the .text() should return TEST, where .val() will return GO

Here's the old-skool non-jQuery version that works in all scriptable browsers:
var option = styleSelect.options[styleSelect.selectedIndex];
alert("Value: " + option.value + ", text: " + option.text);

Use first the selector, then the context:
jQuery(':selected',styleSelect).text();
matchew's suggestion will work too but only when you didn't set the value-attributes of the <option>'s
(If you set the value-attributes you will get the value of the selected option instead of the text)

var styleSelect = $('select option:selected');
console.log(styleSelect.val());
Will give you the value of the option currently selected

Related

find a select option with same value as select data-status and load option as "selected" with jquery

I am loading 2 separate ajax responses into a select dropdown and the select dropdown will have a data-status, what I am looking to achieve is to loop through the options and find the option that has the same value as the select data-status and load it as "selected".
Given my html code generated from my ajax call:
<select class="orderCurrentStatus" data-status="1215458">
<option value="608653">Goods Received</option>
<option value="608654">Purchase - Awaiting Payment</option>
<option value="608655">Purchase - Payment Received</option>
<option value="766705">EXCHANGE FEE PAID</option>
<option value="838627">Order Refunded</option>
<option value="1215458">Goods Dispatched</option>
<option value="2322397">Paid - Custom Order Under Production</option>
<option value="2384172">WRONG/INCOMPLETE ADDRESS!</option>
<option value="2544576">Paid - Awaiting Pre-Ordered Items</option>
</select>
My attempt to make it work:
var order_status = $(".orderCurrentStatus").data("status");
var options = $(".orderCurrentStatus option");
if (options.val(order_status)) {
$(this).attr("selected");
}
I just can't get it to work.
You can just use the attribute selector [value="'+ order_status +'"] in order to select an option element that has a value equal to the variable order_status.
From there, set the selected property value to true or selected.
$('.orderCurrentStatus option[value="'+ order_status +'"]').prop('selected', true);
There were a couple issues with your initial code.
The variable this refers to the global object, in this case the window object, since there is no functional scope.
If you don't specify a value when using the .attr() method, the selected attribute value is returned. You need to specify a second parameter in order to set a value for the selected attribute. Specifying true or selected will work in your case. However, the .prop() method is better suited for this since you should be setting the property.
Additionally, if you want to do this for all select elements, then you could iterate over them, then retreive the data-status attribute value, and set the corresponding option element's selected property:
$('select').each(function () {
var status = $(this).data("status");
$(this).find('option[value="'+ status +'"]').prop('selected', true);
});
You should somehow check if an option with the value specified exists! This what you actually tried is assigning a value to every option element.
This should be simple solution:
var order_status = $(".orderCurrentStatus").data("status");
if( $('.orderCurrentStatus option[value=' + order_status + ']').length )
$('.orderCurrentStatus option[value=' + order_status + ']').attr('selected','selected');
You could verify the code on JSFiddle:
https://jsfiddle.net/cwma9h5m/
You can always iterate through the option values to match with the data-status value.
var status = $('.orderCurrentStatus').data("status");
$('.orderCurrentStatus option').each(function(){
if( $(this).val()==status){
$(this).prop('selected', true);
}
});

How to get attribute from selected option of select in jQuery?

I have the next selectbox in HTML:
<select id="listbox-taskStatus" class="selectpicker">
<option status="0">In progress</option>
<option status="1">Not started</option>
<option status="2">Done</option>
<option status="3">Failed</option>
</select>
I want to read the attribute value from selected option.
If just to take the value, it's simple:
var value = $('#listbox-taskStatus').val();
But what should I do, if I want to get the attribute value from selected option?
I know, that .attr() must help, but when I tried to use it I've got the incorrect result.
I've tried the next:
var status = $('#listbox-taskStatus option').attr('status');
But the returned value is always 0 despite on fact I was selecting different option.
What's wrong, how to solve my problem?
Use :selected Selector
var status = $('#listbox-taskStatus option:selected').attr('status');
However, I would recommend you to use data- prefixed attribute. Then you can use .data()
var status = $('#listbox-taskStatus option:selected').data('status');
DEMO
var optionAttr1 = $('#listbox-taskStatus').find('option:selected').attr("status");
var optionAttr = $('#listbox-taskStatus option:selected').attr("status");

outerHTML and attribute updates

I'm trying to get the HTML code as a string with the attribute updates.
I've a select tag, whose options I update using JavaScript.
By default, a first option is selected using the HTML attribute selected="selected".
If I unset selected from the first option using option1.selected = false and set option2.selected = true for the second option, and then call the outerHTML of a select, I get
<select>
<option selected="selected">one</option>
<option>two</option>
<option>three</option>
</select>
As you can see, selected attribute is still on the first option, while it has been moved to the second option. The expected result is
<select>
<option>one</option>
<option selected="selected">two</option>
<option>three</option>
</select>
Here's an example http://jsbin.com/adAbAMe/2/edit?html,js,console,output (click run with js to get a result) which shows, that if a selected attribute has been changed, it doesn't change in the HTML code.
But I need to get the final HTML from outerHTML with the successful attribute updates, because if I move this select somewhere I won't get any updates I've made before using JavaScript.
Is there any method to get the HTML as a string with the real attributes values?
The selected attribute isn't automatically updated, but you can set it to be removed and added to the proper elements.
//remove "selected" from first
if (i==0) {
option.selected = false;
option.removeAttribute("selected");
}
//add "selected" to second
if (i==1) {
option.selected = true;
option.setAttribute("selected", "selected");
}
Here's a working fiddle.
You can use
option.setAttribute('selected', 'selected');
and
option.removeAttribute('selected');
Try
$('button').click(function () {
console.log($('select').prop('outerHTML'))
})
$('select').change(function(){
$(this).find('option[selected]').removeAttr('selected');
$(this).find('option:selected').attr('selected', 'selected');
})
Demo: Fiddle
From the DOM Specification:
selected of type boolean
Represents the current state of the corresponding form control, in an interactive user agent. Changing this attribute changes the state of the form control, but does not change the value of the HTML selected attribute of the element.
(emphasis mine)
To get the effect you're looking for, you want option.setAttribute('selected', 'selected'), though you'll also need option.removeAtrribute('selected') on the other options.

Jquery Mulitple select field error

I have multiple select field each with multiple options.
So, by using jquery to get the respective selected options content, I would be able to get the selected option content. However, this work for the first select field. But, does not work for others. Others keep referencing the first select field selected options content, instead of it owns. Please guide me! Thanks!
My Select fields
<select id="resource_dd" name="resource_dd">
<option selected="selected" value="nil1">No resources.</option>
<option value="1">Week1</option>
<option value="2">Resource1</option>
</select>
<select id="module_dd" name="module_dd">
<option selected="selected" value="nil2">No restriction.</option>
<option value="1">IT1234</option>
<option value="2">IT2345</option>
</select>
Jquery to retrieve the selected content.
$("#module_dd").change(function ( event ) {
var option = $("this").children();
var module_id = $(option+":selected").val(); //module_id get 'nil1' as content instead of nil2
});
Just try this, it will give you the selected value.
$("#module_dd").change(function ( event ) {
var module_id = $(this).val();
});
First of all, you should be saying $(this) instead of $("this").
Second, $(event.target) is probably more appropriate here.
Third, using .children as in $(event.target).children(":selected") will get you what you want.
This is happening because you are referencing $("#module_dd").
You need to add another function and change that to $("#resource_dd") to get the other select field.
Problem code
var option = $("this").children();
var module_id = $(option+":selected").val();
You can't concat a selector string to a jQ collection object. You need to filter the option collection for those which are selected either by:
var option = $( this ).children(":selected");
Or
var option = $( this ).children();
var module_id = option.filter(":selected").val();
Please see Eli Courtwright's answer, but in addition to that, you should do something like $("select") or $("#module_dd, #resource_dd") to target both select fields.

How to get Javascript Select box's selected text

This things works perfectly
<select name="selectbox" onchange="alert(this.value)">
But I want to select the text. I tried in this way
<select name="selectbox" onchange="alert(this.text)">
It shows undefined.
I found how to use DOM to get text. But I want to do this in this way, I means like using just this.value.
this.options[this.selectedIndex].innerHTML
should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.
In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options of the select are accessed, and the SelectedIndex is used to choose the selected one, then its text is being accessed.
Read more about the select DOM here.
Please try this code:
$("#YourSelect>option:selected").html()
Just use
$('#SelectBoxId option:selected').text(); For Getting text as listed
$('#SelectBoxId').val(); For Getting selected Index value
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
If you want to get the value, you can use this code for a select element with the id="selectBox"
let myValue = document.querySelector("#selectBox").value;
If you want to get the text, you can use this code
var sel = document.getElementById("selectBox");
var text= sel.options[sel.selectedIndex].text;
The question was not for the value but for the text.
Imagine you have something like :
<select name="select">
<option value="1">0.5</option
<option value="2">0.7</option
</select>
And you need to catch the text.
So for me I have tried with html (php), and
this.options[this.selectedIndex].text
(from Delan Azabani) doesn't work but
this.options[selectedIndex].text
work, like this on HTML
<select ... onChange="upTVA(this.options[selectedIndex].text);">
It is still surprising that for a select this.text does not work while this.value works

Categories

Resources