JavaScript、jQuery - 检索下拉列表中的项目名称

标签 javascript jquery ruby-on-rails

我试图弄清楚如何获取所选产品的名称label_method: :name,如表单中所示。我可以检索所选项目的 id,如 js 部分所示。

_form.html.erb

<%= f.simple_fields_for :items, wrapper: false do |builder| %>

<%= builder.input :product_id, collection: Product.all, 
    label_method: :name, value_method: :id, label: false, 
    placeholder: 'Type or select item', input_html: { :multiple => true, 
    id: 'select2-product' } %>

js

$("#select2-product").click(function() {
 var selectedItem = $(this);
 console.log("selectedItem " + selectedItem);
 console.log("selectedItem.val() " + selectedItem.val());
});

控制台输出

 selectedItem [object Object] 
 selectedItem.val() 1 

观察

selectedItem.val() 给出下拉列表中所选元素的 :id

selectedItem.text() 给出下拉列表中的所有项目。我怎样才能只选择一个?正如@Amir 的回答

最佳答案

这应该可行,实际上您需要选择 text 而不是 value,因此 text() 为您提供实际的文本该项目

console.log("selectedItem.text() " + selectedItem.text());

<强> Live demo

$('selectedItem:selected').text() for the selected text specifically

关于JavaScript、jQuery - 检索下拉列表中的项目名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192268/

相关文章:

javascript - 在文档加载时触发 materialize.css toast

ruby-on-rails - 在 application.rb 中将 enforce_available_locales 设置为 true 会使测试变慢

ruby-on-rails - 西里尔字符串 Я̆ Я̄ Я̈ 在 ruby​​ 和其他编程语言中返回长度 2 而不是 1

javascript - 如何在特定位置动态添加列?

javascript - 如何深入理解Javascript的var作用域和闭包?

javascript - 跨站脚本攻击,麻烦

ruby-on-rails - rails : What's the difference between capture and content_for?

javascript - 正则表达式连续匹配

javascript - 在弹出的 javascript 上阻止屏幕

javascript - 我尝试从 javascript 对象检索 `employee info` 但在检查 javascript 控制台时出错