如果variable为null,则使用jQuery将值设置为0?

时间:2010-08-20 01:07:22

标签: javascript jquery

我正在验证某些字段并检查select元素的长度是否大于0.我得到错误“'length'为null或不是对象”因为id $ = SelectResult是一个列表框而且没有值因此返回null和var val = $(this).val();不喜欢那样。

function checkControls() {
  var itemLevel = $("select[title='Item Level']").val();
  switch (itemLevel) {
    case 'Strategic Objective':

 var controlsPassed = 0;


    $("input[id$=UserField_hiddenSpanData],input[title=Title],select[id$=SelectResult]").each(function(){


        var val = $(this).val();
        if(val != 0 && val.length != 0) { 

            //add one to the counter
            controlsPassed += 1;
        }

        });
return (controlsPassed == 3) 

    case 'Milestone Action':

      var controlsPassed = 0;


    $("input[title=Target Date],select[id$=SelectResult],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic 

Objective],select[title=Strategic Priority]").each(function(){


        var val = $(this).val();
        if(val != 0 && val.length != 0) { 

            //add one to the counter
            controlsPassed += 1;
        }

        });
return (controlsPassed == 7) 

case 'Performance Measure':

      var controlsPassed = 0;


    $("select[title=Strategic Objective],input[title=Title],select[id$=SelectResult],select[title=Strategic Priority]").each(function(){

        var val = $(this).val();
        if(val != 0 && val.length != 0) { 

            //add one to the counter
            controlsPassed += 1;
        }

        });
return (controlsPassed == 4) 


    case 'Strategic Priority':

      var controlsPassed = 0;


    $("input[title=Target Date],select[id$=SelectResult],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic 

Objective]").each(function(){   

        //var ResponsibleBusiness = $("select[id$=SelectResult]").val();
        var val = $(this).val();
        if(val != 0 && val.length != 0) { 

            //add one to the counter
            controlsPassed += 1;
        }

        });
return (controlsPassed == 6) 
  }
}

function PreSaveItem() {
            return checkControls()
    }

2 个答案:

答案 0 :(得分:0)

如果我正确理解你的目标,你可以将其简化为:

if(!$("select[id$=SelectResult]").val()) return false;
return $("input[title=Target Date],input[title=Title],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective]").filter(function(){
         return $(this).val() == '';
       }).length > 0;

答案 1 :(得分:0)

更改此行:

if(val != 0 && val.length != 0) { 

if ( !!val && val.length > 0) {