问题
I would like to Get text of select option's label and populate it in a hidden input field.
I can get the value but i would like to know how to populate the hidden field when option is selected or changed. I am actually a jquery newbie so i really have no idea of the event associated with select option.
回答1:
Fiddle : http://jsfiddle.net/m5A9U/
Code
Assuming your HTML is
<select id="select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<input type='hidden' id='hidden' value=''/>
jquery code would be
$("#select").change(function () {
$("#hidden").val($(this).val());
//alert($(this).val())
})
EDIT To get the label of the selected option try
$("#hidden").val($(this).find('option:selected').text());
Updated example : http://jsfiddle.net/m5A9U/1/
回答2:
I've just created this simple jsFiddle. Follow the comments for a better comprehension. There's a solution using pure JavaScript and another one using jQuery.
-- EDIT --
Even if it's not part of your original question, here jsFiddle 2 is the way you can get the "label" instead value.
回答3:
We would need to see some HTML to know exactly how you have your label setup, but here is a basic example:
$("#sel1").change(function () {
$("#myInput").val(($("label[for=" + $(this).attr("id") + "]").text()));
});
Fiddle: http://jsfiddle.net/johnkoer/Lh8Eg/6/
回答4:
To get the option label of select element. We can try this:
<select id="id_select">
<option value="myval_1">Text 1</option>
<option value="myval_2">Text 2</option>
<option value="myval_3">Text 3</option>
</select>
Then write script:
$('#id_select option[value="'+ $('#id_select').val() +'"]').text();
回答5:
If you have a list of values that you want to convert into human readable text based on the text in a select input:
HTML
<div id="current_values"></div>
<select id="id_select">
<option value="1">First Option</option>
<option value="2">Second Option</option>
<option value="3">Third Option</option>
</select>
JavaScript
var values = [1,3];
for(var i = values.length; i >=0; i--){
$("#current_Values").append($('#id_select option[value="'+ values[i] +'"]').text()+"<br>");
}
来源:https://stackoverflow.com/questions/11940680/get-text-of-select-options-label-and-populate-it-in-a-hidden-input-field