If i have the bookd_ids and book_titles as follows in the database:
id | title
---------------
1 | abc
2 | xyz
3 | pqr
I have the books dropdownlist as show below:
<%= select("books", "book_id", Book.all.collect {|b|
[ b.title, b.id ] }, {:include_blank => 'Select Book'})%>
i can get the id of the books thru query this way:
var id = $("#books_book_id").val();
How to get the abc, xyz pqr titles using jquery?
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
Getting the selected ID using the selectedIndex and options properties # The options property returns an HTMLOptionsCollection , an array-like collection of options for a select element. You can pair it with the selectedIndex property to get the selected option . Then, you can use the id property to get its ID.
With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.
var text = $("#books_book_id option:selected").text();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With