Javascript: Get selected option from list and paste it on a label tag
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&开发者_StackOverflow中文版gt;
<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
Two little things:
change selector from
$("#userDto\\.nationality option:selected")
to$("#userDto\\.nationality")
change event handler from
click
tochange
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.
精彩评论