If variable is null set the value to 0 with jQuery?
I am validating some fields and check if the length of a select element is larger than 0. I get the error "'length' is null or not an object" because id$=SelectResult is a listbox and can have no v开发者_JAVA百科alues and therefor return null and var val = $(this).val(); doesn't like that.
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()
}
If I'm understanding your goal correctly, you can shorten it down to this:
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;
Change this line:
if(val != 0 && val.length != 0) {
to
if ( !!val && val.length > 0) {
精彩评论