我做了一些搜索,但我对JavaScript和jQuery很新,似乎无法弄清楚如何去做(或者甚至可能)。基本上,我有两个选择菜单和一个相关的值,每个选项与文本不同,但选择之间相同:
<select id="day1Breakfast">
<option value="">Select One</option>
<option value="bec">Bacon Egg and Cheese</option>
<option value="muf">Muffin</option>
<option value="bag">Bagel</option>
</select>
<select id="day2Breakfast">
<option value="">Select One</option>
<option value="bec">Bacon Egg and Cheese</option>
<option value="muf">Muffin</option>
<option value="bag">Bagel</option>
</select>
我需要做的是根据SELECT ID和OPTION VALUE使用所选文本填充另一个div。例如,如果有人从day2Breakfast SELECT中选择了“Muffin”,我会想要提醒(“你为第2天选择了松饼”)。我知道我可以使用它来查找带有ID的div中的文本:
document.getElementById("day1Breakfast").text()
但那会返回“Bacon Egg and CheeseMuffinBagel”。我只需要检索与特定SELECT ID和OPTION VALUE相关联的文本。
非常感谢!
答案 0 :(得分:7)
您正在寻找元素.value
(在vanilla JavaScript中),并且在jQuery中是.val()
。此外,要获取所选值的文本,只需在元素中请求所有option:selected
:
// Event delegation on all select elements
$("select").on("change", function (e) {
// When a select changes, find the selection option
// Also, get the ID of the select element that changed
var selected = $(this).find("option:selected"),
fromElem = $(this).prop("id");
// Output the new selected text, value, and ID of affected select
console.log( selected.text(), selected.val(), fromElem );
});
答案 1 :(得分:1)
你想要这样的东西,
$("#day1Breakfast option[value='bec']").text();
答案 2 :(得分:0)
<script type="text/javascript">
function fnc(myid,myvalue)
{
alert("you've chosen "+myvalue+" from "+myid);
}
</script>
<select id="day1Breakfast" onChange="fnc(this.id,this.value)">
<option value="">Select One</option>
<option value="bec">Bacon Egg and Cheese</option>
<option value="muf">Muffin</option>
<option value="bag">Bagel</option>
</select>
<select id="day2Breakfast" onChange="fnc(this.id,this.value)">
<option value="">Select One</option>
<option value="bec">Bacon Egg and Cheese</option>
<option value="muf">Muffin</option>
<option value="bag">Bagel</option>
</select>
答案 3 :(得分:0)
我稍微修改了你的HTML。请参阅演示http://jsfiddle.net/j6HU6/8/
HTML:
<select class="menu" name="day 1">
<option value="">Select One</option>
<option value="bec">Bacon Egg and Cheese</option>
<option value="muf">Muffin</option>
<option value="bag">Bagel</option>
</select>
<select class="menu" name="day 2">
<option value="">Select One</option>
<option value="bec">Bacon Egg and Cheese</option>
<option value="muf">Muffin</option>
<option value="bag">Bagel</option>
</select>
JS:
$('.menu').change(function(){
alert('You chose ' + $(this).children('option:selected').text() + ' for ' + $(this).attr('name'));
});