Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct way to get selected option in jquery from an object

I've seen on StackOverflow and googling around that the most used way to get the selected text from a <SELECT> element with jquery is like this

$("#cboId :selected").text()

what I have is not the id, but an object. I have an object, say

var myCombo= $("#cboId");

coming from an earlier piece of code.

I've done like this to get the selected text, but is ugly:

  $("#" + myCombo.attr('id') + " :selected").text() ;

is there any cleaner way to do it?

thanks.

like image 755
pomarc Avatar asked Jun 10 '09 09:06

pomarc


People also ask

How do I select a selected box using jQuery?

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue] , so in your case you can select the option and set the selected attribute. $("div. id_100 > select > option[value=" + value + "]"). prop("selected",true);

How do I get the first select option in jQuery selected?

Select the <select> element using JQuery selector. This selector is more specific and selecting the first element using option:nth-child(1). This will get access to the first element (Index starts with 1).

What is the best way to add options to a select from a JavaScript object with jQuery?

Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method.


1 Answers

var selectedText = $(":selected",myCombo).text();
like image 52
Philippe Leybaert Avatar answered Nov 02 '22 08:11

Philippe Leybaert