返回值:String, Arrayval()
Get the current value of the first element in the set of matched elements.
-
1.0 新增val()
The .val()
method is primarily used to get the values of form elements. In the case of <select multiple="multiple">
elements, the .val()
method returns an array containing each selected option.
For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:
$('select.foo option:selected').val(); // get the value from a dropdown select $('select.foo').val(); // get the value from a dropdown select even easier $('input:checkbox:checked').val(); // get the value from a checked checkbox $('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons
示例:
Get the single value from a single select and an array of values from a multiple select and display their values.
<!DOCTYPE html>
<html>
<head>
<style>
p { color:red; margin:4px; }
b { color:blue; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<p></p>
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<select id="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<script>
function displayVals() {
var singleValues = $("#single").val();
var multipleValues = $("#multiple").val() || [];
$("p").html("<b>Single:</b> " +
singleValues +
" <b>Multiple:</b> " +
multipleValues.join(", "));
}
$("select").change(displayVals);
displayVals();
</script>
</body>
</html>
演示:
示例:
Find the value of an input box.
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; margin:8px; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<input type="text" value="some text"/>
<p></p>
<script>
$("input").keyup(function () {
var value = $(this).val();
$("p").text(value);
}).keyup();
</script>
</body>
</html>