我正在从MySQL中检索一些数据并将其写入某些选择标签,然后我检索每个选定的选项值并将其显示在DIV中,这里是javascript:
function main() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div#one").text(str);
})
.trigger('change');
}
所以,我希望每个检索到的值都写在单独的输入中:
First value: <input type="text" id="test" />
Second value: <input type="text" id="test2" />
Third value: <input type="text" id="test3" />
我该怎么做?非常感谢!
答案 0 :(得分:1)
简单选择始终具有选定值,因此您可以尝试这样的事情:
$(function() {
$("select").change(function() {
var str = "";
$("select").each(function() {
str += $(this).val()+"<br/>";
});
$("div#one").html(str);
});
});
您可以在此处查看:http://jsfiddle.net/vJdUt/
答案 1 :(得分:0)
//empty div at start using .empty()
$("select").change(function () {
//get the selected option's text and store it in map
var map = $("select :selected").map(function () {
var txt = $(this).text();
//do not add the value to map[] if the chosen value begins with "Select"
return txt.indexOf("Select") === -1 ? txt + " , " : "";
}).get();
//add it to div
$("#one").html(map);
});
//empty textboxes at start using .val("")
$("select").change(function () {
var text = $(":selected", this).text() //this.value;
//get the index of the select box chosen
var index = $(this).index();
//get the correct text box corresponding to chosen select
var $input = $("input[type=text]").eq(index);
//set the value for the input
$input.val(function () {
//do not add the value to text box if the chosen value begins with "Select"
return text.indexOf("Select") === -1 ? text : "";
});
});