我正在尝试制作一个程序,在其中显示菜单中选择的值。我不明白为什么<select> tag不起作用。
HTML
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src='script.js'></script>
</head>
<body>
<form>
<Label for="country">Country</Label>
<select name="country" id= "country">
<option name="country" id="country">Country</option>
<option name="USA" id="country">USA</option>
<option>India</option>
<option>China</option>
<option>France</option>
<option>England</option>
<option>Ecuador</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit"></input>
</form>
<p id="demo"></p>
</body>
</html>
脚本
var country=$('#country :selected');
document.getElementById("demo").innerHTML = country;
答案 0 :(得分:2)
始终唯一地使用ID属性,您使用它3次,考虑使用类。
这就是你想要的:
//Wait until the page is ready for manipulation
$(function(){
//Whenever the value of #country changes, do:
$("#country").on('change', function() {
//Get the new value
var country = $(this).val();
//Put the new value into the #demo element
$("#demo").html(country);
});
});
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
</head>
<body>
<form>
<Label for="country">Country</Label>
<select name="country" id="country">
<option value="" disabled selected>Select your country</option>
<option value="USA">USA</option>
<option value="india">India</option>
<option value="china">China</option>
<option value="france">France</option>
<option value="england">England</option>
<option value="ecuador">Ecuador</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit"></input>
</form>
<p id="demo"></p>
</body>
</html>
答案 1 :(得分:1)
您的脚本必须放在文档的结束或 $(document).ready(..)
,如下所示。
请确保订阅至.change()
活动,每次selected value
更改时,都将其放置在您想要的位置。
$(document).ready(function() {
$('#country').change(function() { // every times is changed
$('#demo').html($(this).val()); // add value in tag with id #demo
});
});
$(document).ready(function() {
$('#country').change(function() { // every times is changed
$('#demo').html($(this).val()); // add value in tag with id #demo
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<form>
<Label for="country">Country</Label>
<select name="country" id="country">
<option>Country</option>
<option>USA</option>
<option>India</option>
<option>China</option>
<option>France</option>
<option>England</option>
<option>Ecuador</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit"></input>
</form>
<p id="demo"></p>