元素取值val()
val()方法主要用来获取form元素的值像input select textarea。在对select取值的时候当没有option被选定时val()会返回null,至少一个option被选定时val()会返回一个包含所有selected的option。
对于selects和checkboxs,你可以使用:selected和:checked选择器来获取值,例如:
//Get the value from a dropdown select
$("select.foo option:selected").val(); //Get the value from a dropdown select even easier
$("select.foo").val(); //Get the value from checked checkbox
$("input:checkbox:checked").val(); //Get the value from a set of radio buttons
$("input:radio[name=bar]:checked").val()
Note: At present, using .val()
on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:
Example:
1. 从单选下拉框取单一值,从多选下拉框取Arrary值
function displayVals(){
var singleValues = $("#single").val();
var multipleValues = $("#multiple").val() || [];
$("p").html("<b>Single:</b>"+singleValues+
" <b>Multiple:</b> " + multipleValues.join(", "));
}
$("select").change(displayVals);
2. 获取input box的值
$("input").keyup(function(){
var value = $(this).val();//不错
$("p").text(value);
}).keyup();
Field的值不能为空,一般是一个String。要测试String是否为NULL,你可以测试它是不是empty string,代码如下:
if($(selector).val() != '') {}
或者:
if($(selector)).val().length() !=0) {}
如果要排除空格影响可以使用$.trim():
if($.trim($(selector).val()) != '') {}
如果要先判断元素是否存在可以用如下代码:
// the $(selector) will return an Array, if element not exist the length is equal 0
if($(selector).length){
//exit
}