$(select).val().length of null 给出错误

$(select).val().length of null gives error

我的表单中有一个 select 对象,其样式使用 Bootstrap-select.js 插件。当我初始化 select 框并尝试获取它的值时,它是 null 直到我 select 一个选项。在我的脚本中,我使用的是:-

$(select).val().length

但是,当 $(select).val()null 时,这会出错。我真的很想得到一个 0.

我该怎么做?

试试这个

function get_length( select ){
 if ( $(select).val() != null ) {
  return $(select).val().length;
 }else{
  return 0;
 }
}

console.log( get_length(my_select_box_variable) );

使用这个。

var $selectElement = $("#mySelect");
var len = $selectElement.val() != null ? $selectElement.val().length : 0;
console.log(len);

尝试:-

($(select).val() || '').length

Logical Operators

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

Examples of expressions that can be converted to false are:

  • null
  • NaN
  • 0
  • empty string ("")
  • NaN
  • undefined

演示

var length = ($('select').val() || '').length;

console.log('length: ' + length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>

<select>