If variable is null set the value to 0 with jQuery? - javascript

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 values 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) {

Related

How to make function simple

Maybe delete some logical Operators, make a "Check function "?
Or connect some logical in one piece?
// Function
function getTicketPrice(childNumber,adultNumber){
if (childNumber > 2 && adultNumber > 2) {
return "-";
}
if (childNumber == 2 && adultNumber == 3) {
return "-";
}
if (childNumber == 3 && adultNumber == 2) {
return "-";
}
var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("Ticket");
var row = getTicketPriceChild(childNumber, sheet);
var col = getTicketPriceAdult(adultNumber, sheet);
if (row >-1 && col === undefined) {
return "-";
}
if (row === undefined && col >-1) {
return "-";
}
var value = sheet.getRange(row, col).getValue();
if(value > 1){
return value;
} else {
return '-';
}
}
Something like this:
function getTicketPrice(childNumber, adultNumber) {
if ((childNumber > 2 && adultNumber > 2) || (childNumber == 2 && adultNumber == 3) || (childNumber == 3 && adultNumber == 2))
return "-";
const sheet = SpreadsheetApp.openByUrl(url).getSheetByName('Ticket');
const row = getTicketPriceChild(childNumber, sheet);
const col = getTicketPriceAdult(adultNumber, sheet);
if ((row > -1 && col === undefined) || (row === undefined && col > -1))
return "-";
const value = sheet.getRange(row, col).getValue();
return value > 1 ? value : "-"
}

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

JS Empty focused Input

If the user enters an invalid number, I want to empty the input. Negative numbers and numbers that are decimal are not allowed.
This is my Js Function:
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').html("");
}
$('#priceOutput').html(output);
}
But somehow the input is not empty if I enter a count that goes into the else section.
change the value of the input with val() instead of html():
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').val("");
}
$('#priceOutput').html(output);
}

How to display the names of all controls(textboxes & dropdowns) which are empty in my page

I get the message Validation Failed if any of my controls are empty, but I would want to display the names of the controls which are empty. These controls are dynamically created on the page.
Below is the code that I am using now
function validateinput() {
var arrTextBox = document.getElementsByTagName("input");
var ddlTextBox = document.getElementsByTagName("select");
var retVal = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type == "text" && arrTextBox[i].getAttribute("IsMandatory") == "Y" && arrTextBox[i].value == ""){
retVal = 0;
}
}
for (j = 0; j < ddlTextBox.length; j++) {
if (ddlTextBox[j].getAttribute("IsMandatory") == "Y" && ddlTextBox[j].value == "") {
retVal = 0;
}
}
if (retVal == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
return true;
}
}
Okay, I see from the comments that you need some more specific assistance. Try this:
function validateinput() {
var emptySelects = '';
var emptyTextboxes = '';
var arrTextBox = document.getElementsByTagName("input");
var ddlTextBox = document.getElementsByTagName("select");
var retVal = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type == "text" && arrTextBox[i].getAttribute("IsMandatory") == "Y" && arrTextBox[i].value == ""){
retVal = 0;
emptyTextboxes+= ' ' + arrTextBox[i].name;
}
}
for (j = 0; j < ddlTextBox.length; j++) {
if (ddlTextBox[j].getAttribute("IsMandatory") == "Y" && ddlTextBox[j].value == "") {
retVal = 0;
emptySelects += ' ' + ddlTextBox[j].name;
}
}
if (retVal == 0) {
alert("Validation Failed");
if (emptyTextboxes != '') alert('The following textboxes are empty:' + emptyTextboxes);
if (emptySelects != '') alert('The following selections are empty:' + emptySelects);
return false;
}
else {
alert("Validation Success");
return true;
}
}

Validate different fields depending on what is selected in a dropdown in a form with jQuery?

I have the following code to validate some fields on a sharepoint newform.aspx. To not submit the form in sharepoint I must return a false statement to the default function PreSaveItem.
Validation:
//bind a change event to all controls to validate
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").change(function(){
checkControls()
});
//the change event function - check the status of each control
function checkControls(){
//set a variable to count the number of valid controls
var controlsPassed = 0;
//set up a selector to pick .each() of the target controls
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").each(function(){
//if the control value is not zero AND is not zero-length
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
//call the PreSaveItem function and pass the true/false statement of 5 valid controls
return (controlsPassed == 5)
}
function PreSaveItem() {
return checkControls()
}
I want to validate different elements depending on what I have selected in a dropdown list called Item Level.
I get the values from Item Level with:
$("select[title='Item Level']").change(function() {
var itemLevel = $(this).val();
if (itemLevel == "Strategic Objective") {
alert(itemLevel);
}
if (itemLevel == "Strategic Priority") {
alert(itemLevel);
}
if (itemLevel == "Milestone Action") {
alert(itemLevel);
}
if (itemLevel == "Performance Measure") {
alert(itemLevel);
}
});
I thought it would be easy to just chuck the validation code into the if's but it doesn't work.
For example:
$("select[title='Item Level']").change(function() {
var itemLevel = $(this).val();
if (itemLevel == "Strategic Objective") {
alert(itemLevel);
}
if (itemLevel == "Strategic Priority") {
alert(itemLevel);
}
if (itemLevel == "Milestone Action") {
//bind a change event to all controls to validate
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").change(function(){
checkControls()
});
//the change event function - check the status of each control
function checkControls(){
//set a variable to count the number of valid controls
var controlsPassed = 0;
//set up a selector to pick .each() of the target controls
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").each(function(){
//if the control value is not zero AND is not zero-length
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
//call the PreSaveItem function and pass the true/false statement of 5 valid controls
return (controlsPassed == 5)
}
function PreSaveItem() {
return checkControls()
}
alert(itemLevel);
}
if (itemLevel == "Performance Measure") {
alert(itemLevel);
}
});
and in the item level item Strategic Objective validate some other elements. Any ideas?
Thanks in advance.
Edit: the working code with help from casablanca:
function checkControls() {
var itemLevel = $("select[title='Item Level']").val();
switch (itemLevel) {
case 'Strategic Objective':
var controlsPassed = 0;
$("input[id$=UserField_hiddenSpanData]").each(function(){
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if(val != 0 && val.length != 0 && txt.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 1)
case 'Milestone Action':
var controlsPassed = 0;
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").each(function(){
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 5)
case 'Performance Measure':
var controlsPassed = 0;
$("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 == 2)
case 'Strategic Priority':
var controlsPassed = 0;
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective]").each(function(){
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 4)
}
}
function PreSaveItem()
{
return checkControls()
}
Okay, so this is the problem I see in your current script: binding an event handler is permanent, so if you choose "Milestone Action" even once and then switch to another option, you will still validate the original selection.
You can do away with all the change handlers and instead add your conditions directly in checkControls, validating the necessary elements based on the current selection. I've also replaced your ifs with a switch since it's cleaner:
function checkControls() {
var itemLevel = $("select[title='Item Level']").val();
switch (itemLevel) {
case 'Strategic Objective':
// Perform validation for this item level
return result; // true or false
case 'Milestone Action':
// Perform validation for this item level
return result; // true or false
// etc...
}
}
Update: For example, if when "Milestone Action" is selected, you would like to check if some text field is not empty, then under case 'Milestone Action':, you would add something like this:
if ($('something').val().length > 0)
return true;
else
return false;
Edit: If you have access to the form code (I'm not familiar with SharePoint), you should assign IDs to your form elements so you can reference them like $('#itemLevel') instead of having to use a long selector.

Categories

Resources