views:

50

answers:

2

Hi, 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">
 <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> 

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

+1  A: 

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 }}')")
eliocs
+1  A: 

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);
Nick Craver
@Nick: slow down, I'm seeing way too many typos from you today ;-)
Andy E
@Andy - Distracted by this: http://stackoverflow.com/questions/3541541/how-to-know-which-jquery-button-was-clicked-in-list-context jQuery UI wipes the value out it seems, not sure who made that wise decision, throwing me off :'(
Nick Craver
this works and helps me understand jQuery's philosophy. thanks!
eliocs