从选择元素中获取选择的选项 [英] Get selected option from select element

查看:56
本文介绍了从选择元素中获取选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试从下拉列表中获取选定的选项,并使用该文本填充另一个项目,如下所示. IE正在风起云涌,它在Firefox中不起作用:

I am trying to get the selected option from a dropdown and populate another item with that text, as follows. IE is barking up a storm and it doesn't work in Firefox:

$('#ddlCodes').change(function() {
  $('#txtEntry2').text('#ddlCodes option:selected').text();
});

我在做什么错了?

推荐答案

以下是简短版本:

$('#ddlCodes').change(function() {
  $('#txtEntry2').text($(this).find(":selected").text());
});

karim79 表现不错,根据您的元素名称txtEntry2可能是一个文本框(如果有的话)输入,则需要使用.val().text()这样:

karim79 made a good catch, judging by your element name txtEntry2 may be a textbox, if it's any kind of input, you'll need to use .val() instead or .text() like this:

  $('#txtEntry2').val($(this).find(":selected").text());

对于怎么了?"问题的一部分:.text()不带选择器,它带您想要设置为的文本,或者什么也不能返回已经存在的文本.因此,您需要获取所需的文本,然后将其放在要设置的对象的.text(string)方法中,就像我上面提到的那样.

For the "what's wrong?" part of the question: .text() doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string) method on the object you want to set, like I have above.

这篇关于从选择元素中获取选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆