开发者

Selecting an option by its text

开发者 https://www.devze.com 2023-01-12 09:17 出处:网络
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'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.

An extract of my code:

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 form elements

 <p><label for="id_propietario">Propietario:</label> <select name="propietario" id="id_propietario">
 <op开发者_StackOverflow社区tion 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> 

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 }}');

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?

Thanks in advance

p.s: it's my first time using jQuery


Just found something that works, using contains instead of the text='values' selector

not working for me

$("#id_adeudado option[text='{{ usuario.username }}']")

working

$("#id_adeudado option:contains('{{ usuario.username }}')")


You can check like this to get the text of the selected <option> (for your first code block):

$("#id_adeudado :selected").text();

And this to set the selected <option> value by the text:

$("#id_adeudado option").filter(function() {
  return this.value == '{{ usuario.username }}';
}).attr('selected', true);
0

精彩评论

暂无评论...
验证码 换一张
取 消