通过文本选择一个选项 [英] Selecting an option by its text
问题描述
我正在使用django开发一个网页,我想使用jQuery向表单添加一些JavaScript。基本上,我想根据另一个选择以一种形式选择一个选项。
我需要使用选项的文本而不是选项的值,因为选项的值由django动态生成。
I'm developing a web page using django and I want to add some javascript to a form using jQuery. Basically I want to select an option in a form depending on an another selection. I need to use option's text and not option's values because option's values are generated dynamically by django.
我的代码摘录:
javascript
$("#id_propietario").change(
function() {
if ($("#id_propietario :selected").text() == '{{ usuario.username }}') {
alert('test');
} else {
$("#id_adeudado").val($("#id_adeudado option[text='{{ usuario.username }}']").val());
}
}
);
html表单元素
<p><label for="id_propietario">Propietario:</label> <select name="propietario" id="id_propietario">
<option value="" selected="selected">---------</option>
<option value="1">elio</option>
<option value="2">up1</option>
<option value="3">up2</option>
</select></p>
<p><label for="id_adeudado">Adeudado:</label> <select name="adeudado" id="id_adeudado">
<option value="" selected="selected">---------</option>
<option value="1">elio</option>
<option value="2">up1</option>
<option value="3">up2</option>
</select></p>
我使用的是jQuery 1.4,这个行为显然已经从1.3变为1.4,你可以直接使用
I'm using jQuery 1.4, this behavior apparently has changed from 1.3 to 1.4 where you could directly use
$("#id_adeudado").val('{{ usuario.username }}');
请注意,django正在使用当前用户名替换{{usuario.username}}。我的代码不起作用,因为jQuery没有使用text ='value'选择器选择选项元素。
我如何克服这个问题?
Note that django is replacing {{ usuario.username }} with the current username. My code isn't working because jQuery isn't selecting the option element using the text='value' selector. How can I overcome this problem?
提前感谢
ps:这是我的第一次使用jQuery
p.s: it's my first time using jQuery
推荐答案
您可以这样检查以获取所选< option>
(对于您的第一个代码块):
You can check like this to get the text of the selected <option>
(for your first code block):
$("#id_adeudado :selected").text();
这样设置选择的< option>
value由文本:
And this to set the selected <option>
value by the text:
$("#id_adeudado option").filter(function() {
return this.value == '{{ usuario.username }}';
}).attr('selected', true);
这篇关于通过文本选择一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!