I am trying to turn this code into a correct for loop statement, so that I can save my repetitions. I have tried my best to get it done, but I just don't know how I can write it correctly:
function myProg() {
var luckyNumber = 3;
var luckyNumber2 = 5;
var luckyNumber3 = 8;
var firstInput = document.luckForm.numberBox.value;
var secondInput = document.luckForm.numberBox2.value;
var thirdInput = document.luckForm.numberBox3.value;
var temp = '';
if (firstInput == luckyNumber && secondInput == luckyNumber2 && thirdInput == luckyNumber3 || firstInput == luckyNumber && secondInput == luckyNumber3 && thirdInput == luckyNumber2 || firstInput == luckyNumber2 && secondInput == luckyNumber3 && thirdInput == luckyNumber || firstInput == luckyNumber2 && secondInput == luckyNumber && thirdInput == luckyNumber3 || firstInput == luckyNumber3 && secondInput == luckyNumber && thirdInput == luckyNumber2 || firstInput == luckyNumber3 && secondInput == luckyNumber2 && thirdInput == luckyNumber)
{
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!');
}
}
try something like this:
Array.prototype.getDuplicates = function() {
var cache = {}, results = [], that = this;
that.forEach(function(item, index) {
if(!cache.hasOwnProperty(item) && that.lastIndexOf(item) > index) {
results.push(item);
}
cache[item] = true;
});
return results;
}
var answers = [luckyNumber, luckyNumber2, luckyNumber3];
var indexes = [answers.indexOf(firstInput), answers.indexOf(secondInput), answers.indexOf(thirdInput)];
if(indexes.indexOf(-1) === -1 && indexes.getDuplicates().length === 0) {
// alert("Whatever");
}
Here's an example without using array. Input check was added.
function myProg() {
var numbersToMatch = 3;
var luckyNumbers = {n1: 3, n2: 5, n3: 8};
var firstInput = parseInt(document.luckForm.numberBox.value);
var secondInput = parseInt(document.luckForm.numberBox2.value);
var thirdInput = parseInt(document.luckForm.numberBox3.value);
if (isNaN(firstInput) || isNaN(secondInput) || isNaN(thirdInput)) {
alert('All inputs must be numbers!');
return;
}
var inputs = {n1: firstInput, n2: secondInput, n3: thirdInput};
var matches = {n1: false, n2: false, n3: false};
for (var i in inputs) {
for (var j in luckyNumbers) {
if ((!matches[j]) && (luckyNumbers[j] == inputs[i])) {
matches[j] = true;
numbersToMatch--;
break;
}
}
}
if (numbersToMatch == 0) {
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!');
}
}
Related
I am working on node js and mysql here i am using profile incomplete or complete logic so i have to check all the fields or empty or not so i have 28 fields i have used 28 if else can we make shorter code.
Here my code
so how we can reduce my code if we can reduce our code please share your solution.
Here no error this code is correct But I need to make shorter code it will be good.
let points = 0;
let point1 = 0;
let point2 = 0;
let point3 = 0;
let point4 = 0;
let point5 = 0;
let point6 = 0;
let point7 = 0;
let point8 = 0;
let point9 = 0;
let point10 = 0;
let point11 = 0;
let point12 = 0;
let point13 = 0;
let point14 = 0;
let point15 = 0;
let point16 = 0;
let point17 = 0;
let point18 = 0;
let point19 = 0;
let point20 = 0;
let point21 = 0;
let point22 = 0;
let point23 = 0;
let point24 = 0;
let point25 = 0;
let point26 = 0;
if (profileRes[0].username == null || profileRes[0].username == "") {
point1 = points + 10;
} else if (profileRes[0].username != null || profileRes[0].username != "") {
point1 = points += 0;
}
if (profileRes[0].phone == null || profileRes[0].phone == "") {
point2 = points + 10;
} else if (profileRes[0].phone != null || profileRes[0].phone != "") {
point2 = points += 0;
}
if (profileRes[0].email == null || profileRes[0].email == "") {
point3 = points + 10;
} else if (profileRes[0].email != null || profileRes[0].email != "") {
point3 = points += 0;
}
if (profileRes[0].company_name == null || profileRes[0].company_name == "") {
point4 = points + 10;
} else if (profileRes[0].company_name != null || profileRes[0].company_name != "") {
point4 = points += 0;
}
if (profileRes[0].profile_description == null || profileRes[0].profile_description == "") {
point5 = points + 10;
} else if (profileRes[0].profile_description != null || profileRes[0].profile_description != "") {
point5 = points += 0;
}
if (profileRes[0].short_description == null || profileRes[0].short_description == "") {
point6 = points + 10;
} else if (profileRes[0].short_description != null || profileRes[0].short_description != "") {
point6 = points += 0;
}
if (profileRes[0].company_url == null || profileRes[0].company_url == "") {
point7 = points + 10;
} else if (profileRes[0].company_url != null || profileRes[0].company_url != "") {
point7 = points += 0;
}
if (profileRes[0].company_linkedin == null || profileRes[0].company_linkedin == "") {
point8 = points + 10;
} else if (profileRes[0].company_linkedin != null || profileRes[0].company_linkedin != "") {
point8 = points += 0;
}
if (profileRes[0].company_instagram == null || profileRes[0].company_instagram == "") {
point9 = points + 10;
} else if (profileRes[0].company_instagram != null || profileRes[0].company_instagram != "") {
point9 = points += 0;
}
if (profileRes[0].company_facebook == null || profileRes[0].company_facebook == "") {
point10 = points + 10;
} else if (profileRes[0].company_facebook != null || profileRes[0].company_facebook != "") {
point10 = points += 0;
}
if (profileRes[0].number_of_employees == null || profileRes[0].number_of_employees == "") {
point11 = points + 10;
} else if (profileRes[0].number_of_employees != null || profileRes[0].number_of_employees != "") {
point11 = points += 0;
}
if (profileRes[0].company_logo == null || profileRes[0].company_logo == "") {
point12 = points + 10;
} else if (profileRes[0].company_logo != null || profileRes[0].company_logo != "") {
point12 = points += 0;
}
if (profileRes[0].founding_year == null || profileRes[0].founding_year == "") {
point13 = points + 10;
} else if (profileRes[0].founding_year != null || profileRes[0].founding_year != "") {
point13 = points += 0;
}
if (profileRes[0].is_profile_published == null || profileRes[0].is_profile_published == "") {
point14 = points + 10;
} else if (profileRes[0].is_profile_published != null || profileRes[0].is_profile_published != "") {
point14 = points += 0;
}
if (profileRes[0].legal_name == null || profileRes[0].legal_name == "") {
point15 = points + 10;
} else if (profileRes[0].legal_name != null || profileRes[0].legal_name != "") {
point15 = points += 0;
}
if (profileRes[0].billing_address == null || profileRes[0].billing_address == "") {
point16 = points + 10;
} else if (profileRes[0].billing_address != null || profileRes[0].billing_address != "") {
point16 = points += 0;
}
if (profileRes[0].zip_code == null || profileRes[0].zip_code == "") {
point17 = points + 10;
} else if (profileRes[0].zip_code != null || profileRes[0].zip_code != "") {
point17 = points += 0;
}
if (profileRes[0].vat_number == null || profileRes[0].vat_number == "") {
point18 = points + 10;
} else if (profileRes[0].vat_number != null || profileRes[0].vat_number != "") {
point18 = points += 0;
}
if (profileRes[0].sdi_codex == null || profileRes[0].sdi_codex == "") {
point19 = points + 10;
} else if (profileRes[0].sdi_codex != null || profileRes[0].sdi_codex != "") {
point19 = points += 0;
}
if (profileRes[0].benefits == null || profileRes[0].benefits == "") {
point20 = points + 10;
} else if (profileRes[0].benefits != null || profileRes[0].benefits != "") {
point20 = points += 0;
}
if (profileRes[0].category == null || profileRes[0].category == "") {
point21 = points + 10;
} else if (profileRes[0].category != null || profileRes[0].category != "") {
point21 = points += 0;
}
if (profileRes[0].branch == null || profileRes[0].branch == "") {
point22 = points + 10;
} else if (profileRes[0].branch != null || profileRes[0].branch != "") {
point22 = points += 0;
}
if (profileRes[0].coreActivities == null || profileRes[0].coreActivities == "") {
point23 = points + 10;
} else if (profileRes[0].coreActivities != null || profileRes[0].coreActivities != "") {
point23 = points += 0;
}
if (profileRes[0].districts == null || profileRes[0].districts == "") {
point24 = points + 10;
} else if (profileRes[0].districts != null || profileRes[0].districts != "") {
point24 = points += 0;
}
if (profileRes[0].legalFormCompany == null || profileRes[0].legalFormCompany == "") {
point25 = points + 10;
} else if (profileRes[0].legalFormCompany != null || profileRes[0].legalFormCompany != "") {
point25 = points += 0;
}
if (profileRes[0].commune == null || profileRes[0].commune == "") {
point26 = points + 10;
} else if (profileRes[0].commune != null || profileRes[0].commune != "") {
point26 = points += 0;
}
else {
}
let pint = point1 + point2 + point3 + point4 + point5 + point6 + point7 + point8 + point9 + point10 +point11 + point12 + point13 + point14 + point15 + point16 + point17 + point18 + point19 + point20 + point21 + point22 + point23 + point24 + point25 + point26;
let percentage = (pint * 100) / 260;
Should all keys in the profileRes[0] have a corresponding points variable? If yes, then something like this might work. This solution will put all of your points into one object instead of a list of variables:
const pointsMap = Object.entries(profileRes[0]).reduce((acc, [key, value]) => {
acc[key] = !!value ? 0 : 10
return acc
}, {})
// returns an object that has key/value pairs accessible by the profileRes[0] keys
// for example, {username: 10, email: 0, phone: 10...}
Note, the above answer uses !!value to determine if the value is truthy. This means values like null and "" will fail. undefined will also fail this check. If a key in profileRes[0] can be undefined and undefined should be considered a valid value, the line can change to be the following instead:
acc[key] = (value === null || value === "") ? 10 : 0
You can remove all the points variables
let points = 0;
for (let key in profileRes[0]) {
if (profileRes[0][key] === null || profileRes[0][key] === '') {
points += 10;
} else {
points += 0;
}
}
let percentage = (points * 100) / 260;
I have the following code to admit decimals:
<input id="precio" type="text" class="form-control" onclick="this.select();" onkeypress="return OnlyDecimal(event, '0.0', 4, 2);"/>
<script>
function OnlyDecimal(e, valInicial, nEntero, nDecimal) {
var obj = e.srcElement || e.target;
var key_code = (document.all) ? e.keyCode : e.which;
var key_val = String.fromCharCode(key_code);
var patron2 = /[\d.]/;
var control = (key_code === 46 && (/[.]/).test(obj.value)) ? false : true;
var existePto = (/[.]/).test(obj.value);
//el tab
if (key_code === 8)
return true;
if (valInicial !== obj.value) {
var TControl = obj.value.length;
if (existePto === false && key_code !== 46) {
if (TControl === nEntero) {
obj.value = obj.value + ".";
}
}
if (existePto === true) {
var subVal = obj.value.substring(obj.value.indexOf(".") + 1, obj.value.length);
if (subVal.length >= nDecimal) {
return false;
}
}
return patron2.test(key_val) && control;
}
else {
if (valInicial === obj.value) {
obj.value = '';
}
return patron2.test(key_val) && control;
}
}
</script>
But when it's at the maximum number of digits allowed and with focus selected, it doesn't allow me to enter numbers to replace the one in the input.
Is there a way to validate this? or how to detect when the input is selected to validate it ?.
The goal is to be able to enter digits in the input when everything is selected. Is there any idea or solution? Is it explained?
you can use selectionStart and selectionEnd like below, if that is what you want
<input id="precio" type="text" class="form-control" onclick="this.select();" onkeypress="return OnlyDecimal(event, '0.0', 4, 2);"/>
<script>
function OnlyDecimal(e, valInicial, nEntero, nDecimal) {
var obj = e.srcElement || e.target;
var key_code = (document.all) ? e.keyCode : e.which;
var key_val = String.fromCharCode(key_code);
var patron2 = /[\d.]/;
var control = (key_code === 46 && (/[.]/).test(obj.value)) ? false : true;
var existePto = (/[.]/).test(obj.value);
var haveSelection = obj.selectionEnd - obj.selectionStart;
//el tab
if (key_code === 8)
return true;
if (valInicial !== obj.value) {
var TControl = obj.value.length;
if (existePto === false && key_code !== 46) {
if (TControl === nEntero) {
obj.value = obj.value + ".";
}
}
if (existePto === true) {
var subVal = obj.value.substring(obj.value.indexOf(".") + 1, obj.value.length);
if (subVal.length >= nDecimal && !haveSelection) {
return false;
}
}
return patron2.test(key_val) && control;
}
else {
if (valInicial === obj.value) {
obj.value = '';
}
return patron2.test(key_val) && control;
}
}
</script>
In cognos 10.2, the js script below was working well for hide/show functionalities, but after migrating to cognos 11.0.12, it's not working fine.
I replaced
node.onpropertychange=ShowOrHide; with node.addEventListener("change", function(){ShowOrHide();}); and it only worked when I changed the radio button values, not on running the report.
The js script is as below:
<script type="text/javascript">
try
{
var cntlName;
var eleTarget1 = document.getElementById('DateRadPrompt');
var node_listDB = eleTarget1.getElementsByTagName('input');
var eleTarget11 = document.getElementById('divGreyOut');
var fW = (typeof getFormWarpRequest == "function" ? getFormWarpRequest() : document.forms["formWarpRequest"]);
if ( !fW || fW == undefined) {
fW = ( formWarpRequest_THIS_ ? formWarpRequest_THIS_ : formWarpRequest_NS_ );}
var list = fW._oLstChoicestodate;
for (var i = 0; i < node_listDB.length; i++)
{
var node = node_listDB[i];
if (node.getAttribute('type') == 'radio')
{
node.addEventListener("change", function(){ShowOrHide();});
}
}
function ShowOrHide()
{
console.log('welcomeShowOrHide');
var DateRadPrompt = document.getElementById('DateRadPrompt');
var eleSource11 = event.srcElement;
if(eleSource11.checked)
{
if (eleSource11.value == 'most_qtr'|| eleSource11.value == 'most_mon1'|| eleSource11.value == 'most_mon2' || eleSource11.value == 'most_mon3' || eleSource11.value == 'cal_prompt' || eleSource11.value == 'most_fsc_yr' || eleSource11.value == 'most_mon12' || eleSource11.value == 'most_qtr4' || eleSource11.value == 'cal_prompt1')
{
eleTarget11.style.display ='none';
}
else
{
eleTarget11.style.display ='block';
}
}
}
list.remove(1);
list.remove(0);
list.removeAttribute("hasLabel");
for (var i=0; i<=node_listDB.length;1++)
{
var nodeDB = node_listDB[i];
if(nodeDB.options[i].selected == true)
{
null
}
else
{
nodeDB.options[0].selected = true
}
}
if (list.options.length==1)
{
eleTarget1.style.display='none';
}
canSubmitPrompt();
}
catch(e)
{
}
</script>`
I have the two functions match and and total working properly. I want the function total project match to divide the first function over the second function multiply times 100. the last function isn't working!
Here is my code so far :
matchContribution.subscribe(function (newValue) {
if (newValue != undefined && newValue != '') {
matchContribution(formatInt(newValue));
var dataValue = Number(matchContribution().replace(/\,/g, ''));
if (dataValue > 999999999999.99 || dataValue < 0) {
matchContribution('');
}
if (loading == false) {
sendCommand('SAVE');
}
}
});
var totalProjectCost = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if (grantRequest() != '' && grantRequest() != undefined) {
hasUserInput = true;
total = total + Number(String(grantRequest()).replace(/\,/g, ''));
}
if (matchContribution() != '' && matchContribution() != undefined) {
hasUserInput = true;
total = total + Number(String(matchContribution()).replace(/\,/g, ''));
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatInt(total);
}
});
var totalProjectMatch = matchContribution()/totalProjectCost();
if(totalProjectMatch>=0)
totalProjectMatch = Math.floor(totalProjectMatch);
else
totalProjectMatch = Math.ceil(totalProjectMatch);
var totalProjectMatch = ko.computed(function () {
var total = 0;
var hasUserInput = false;
if ((grantRequest() != '' && grantRequest() != undefined) && (matchContribution() != '' && matchContribution() != undefined) && (totalProjectCost() != '' && totalProjectCost() != undefined)) {
hasUserInput = true;
total = Number(String(matchContribution()).replace(/\,/g, '')) / Number(String(totalProjectCost()).replace(/\,/g, ''));
total = total * 100;
}
if (total == 0) {
if (!hasUserInput)
return '';
else
return formatInt('0');
}
else {
if (loading == false) {
sendCommand('SAVE');
}
return formatNumber(total);
}
});
I solved the problem! Thanks a lot! Hope that helps other people.
Below is my code. It is supposed to filter a table. It functions great in everything but IE. Can you help?
Perhaps there is a missing tag or something. I've been over it a number of times and could really do with someone's help please!
<script type="text/javascript">
function hasPath(element, cls) {
return (' ' + element.getAttribute('pathway')).indexOf(cls) > -1;
}
function hasLevel(element, cls) {
return (' ' + element.getAttribute('level')).indexOf(cls) > -1;
}
function hasBody(element, cls) {
return (' ' + element.getAttribute('body')).indexOf(cls) > -1;
}
function QualificationSearch() {
var imgdiv = document.getElementById("Chosen_Pathway_img");
var p = document.getElementById("PathwaySelect");
var pathway = p.options[p.selectedIndex].value;
if (pathway == "ALLPATHS") {
pathway = "";
imgdiv.src = "/templates/superb/images/QualChecker/pic_0.png"
}
if (pathway == "ES") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_1.png"
}
if (pathway == "HOUSING") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_2.png"
}
if (pathway == "PLAYWORK") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_3.png"
}
if (pathway == "SC") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_4.png"
}
if (pathway == "YW") {
imgdiv.src = "/templates/superb/images/QualChecker/pic_5.png"
}
var a = document.getElementById("AwardingBodySelect");
var awardingBody = a.options[a.selectedIndex].value;
if (awardingBody == "ALLBODIES") {
awardingBody = "";
}
var levelGroup = document.getElementsByName("LevelGroup");
var chosenLevel = ""
for (var g = 0; g < levelGroup.length; g++) {
if (levelGroup[g].checked) {
chosenLevel += levelGroup[g].value + " ";
}
}
if (chosenLevel == undefined) {
var chosenLevel = "";
} else {
var splitLevel = chosenLevel.split(" ");
var levelA = splitLevel[0];
var levelB = splitLevel[1];
var levelC = splitLevel[2];
var levelD = splitLevel[3];
if (levelA == "") {
levelA = "NOLVL"
}
if (levelB == "") {
levelB = "NOLVL"
}
if (levelC == "") {
levelC = "NOLVL"
}
if (levelD == "") {
levelD = "NOLVL"
}
}
var fil = document.getElementsByName("QList");
for (var i = 0; i < fil.length; i++) {
fil.item(i).style.display = "none";
if ((hasBody(fil.item(i), awardingBody) == true || awardingBody == "") && (hasPath(fil.item(i), pathway) == true || pathway == "") && ((hasLevel(fil.item(i), levelA) == true || hasLevel(fil.item(i), levelB) == true || hasLevel(fil.item(i), levelC) == true || hasLevel(fil.item(i), levelD) == true) || chosenLevel == "")) {
fil.item(i).style.display = "block";
}
}
}
</script>
Check your semicolons. IE is far more strict on that kind of stuff than FF.