views:

22

answers:

1

I have a list of countries, html, they have numeric ids and country name:

Ex:

<select name="userDto.nationality" id="userDto.nationality">
            <option value="">Seleccione</option>
                <option value="1">Alemania</option>
                <option selected="selected" value="2">Argentina</option>
                <option value="8">Australia</option>
                <option value="9">Austria</option>
                <option value="10">Bélgica</option>
                <option value="11">Bolivia</option>
</select>

Im trying to use a jquery script to get the country of the list, not the value, the name and paste it inside of a label.

$(document).ready(function() {      
    $("#userDto\\.nationality option:selected").click(function() { $("#nationalityLabel").html(this.value); });

});

And the HTML that should get the country name is:

<div name="userLabelDiv" id="nationalityUserLabelDiv">
    <label class="required">Nacionalidad :</label>
    <label id="nationalityLabel"></label> 
</div>

Could someone guide me through the problem? I cant find where is my error in the JS code. Thank you

+2  A: 

Two little things:

  • change selector from $("#userDto\\.nationality option:selected") to $("#userDto\\.nationality")

  • change event handler from click to change

Done.

$(document).ready(function() {      
   $("#userDto\\.nationality").change(function() { 
      $("#nationalityLabel").html(this.value);
   });
});

Why:

Your current code would have worked, but only for "Argentinia" since it is selected by default. With your selector option:selected you bound the event handler only to selected option elements, which is, Argentinia.

So you need to add an event handler to the select element itself. The change handler fires whenever you change the selection. I guess that is your desired result.

jAndy
This is working, but my label is getting the id of the option, example: I select "Austria" from the select list and my label shows the id "9", but I actually need it to showme the name of the country that corresponds to the id, in this case, I need the label to show me "Austria". How can I trick that? Thank you!
BoDiE2003