One Function for Multiple Variables - javascript

I am making a sign up sheet app. There are several time slots one can write their name into and submit, showing their name where they have entered it at the corresponding time.
So far I can only get the function to do one name at a time. Is there a way to have it do the same function but for each time slot? Each input field has a corresponding <li> where I wish the input.value to appear. I am trying a switch() to no avail here.
Any help would be greatly appreciated.
Thanks
function addName(e) {
switch(e) {
case 0:
scheduleThree.appendChild(document.createTextNode(inputThree.value));
storeNameInLocalStorage(inputThree.value);
break;
case 1:
scheduleThreeTwoFive.appendChild(document.createTextNode(inputThreeTwoFive.value));
storeNameInLocalStorage(inputThreeTwoFive.value);
break;
}
}
For reference this is the working code for the function to run once. I know there must be a way to do it without writing new functions for each of the 12 time slots.
function addName(e) {
if(inputThree.value === '') {
// alert('Please enter your name');
} else {
scheduleThree.appendChild(document.createTextNode(inputThree.value));
storeNameInLocalStorage(inputThree.value);
}
}
function storeNameInLocalStorage(name) {
let names;
if(localStorage.getItem('names') === null){
names = [];
} else {
names = JSON.parse(localStorage.getItem('names'));
}
names.push(name);
localStorage.setItem('names', JSON.stringify(names));
}
function getNames() {
let names;
if(localStorage.getItem('names') === null){
names = [];
} else {
names = JSON.parse(localStorage.getItem('names'));
}
names.forEach(function(name){
scheduleThree.appendChild(document.createTextNode(name));
inputThree.remove();
inputThreeParent.appendChild(document.createTextNode(name))
})
}

Related

when the function works the else statement is the one that executed

Please Guys some Help Really i stuck here why the else statement works rather than if statement
function add() {
if (input.value !== "") {
localStorage.setItem("name", input.value);
results.innerHTML = `localStorage item <span class='green'>${input.value}</span> been added`;
input.value = '';
}
};
when the add() function add a value from the input i want to check if this value exists in the
localStorage but the else statement that is the one that works
function check() {
if (input.value !== "") {
if (localStorage.getItem(input.value)) {
results.innerHTML = `Found item in Local Storage With Name ${input.value}`;
} else {
results.innerHTML = `No Local Storage with Name <span class='green'>${input.value}</span>`;
}
}
}
You need to get the item by its name. localStorage.getItem(input.value) should be localStorage.getItem("name")

How can I consolidate three functions into one function in order to carry out same functionality?

I have code that detects what the file type is (upon user upload) successfully if this function was separated into three separate functions (one for 2 for photos and 1 for video upload). On my <input/> tags I have onchange="fileValidation()" on each respective input. I'm trying to consolidate this into one function so that it carries out the aforementioned successful functionality when it was separated into three functions.
I'm using vanilla JS. Everything's on a single page. My guess is that it simply won't work correctly if three separate input tags have the same fileValidation() function. In other words - If someone wants to do a video upload, then the other two <input/> tags might get confused... but I could be wrong?
How can I combine all these if()s inside one function so I can get this working again the way it would if separated into three functions? Code below for reference.
function fileValidation() {
const realFileBtn = document.getElementById("real-file");
const realFileW9 = document.getElementById("real-file-w9");
const realFileVideo = document.getElementById("real-file-video");
let filePathWinnerPhoto = realFileBtn.value;
let filePathW9 = realFileW9.value;
let filePathVideo = realFileVideo.value;
// Allowing file type
let allowedExtensionsWinnerPhoto = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let allowedExtensionsW9 = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let allowedExtensionsVideo = /(\.mp4|\.mov)$/i;
if (!allowedExtensionsWinnerPhoto.exec(filePathWinnerPhoto)) {
alert('Invalid file type');
realFileBtn.value = '';
return false;
} else {
console.log("file accepted");
fileAcceptedFlag = true;
}
if (!allowedExtensionsW9.exec(filePathW9)) {
alert('Invalid file type');
realFileW9.value = '';
return false;
} else {
console.log("file accepted");
fileAcceptedW9Flag = true;
}
if (!allowedExtensionsVideo.exec(filePathVideo)) {
alert('Invalid file type');
realFileVideo.value = '';
return false;
} else {
console.log("file accepted");
fileAcceptedVideoFlag = true;
}
return fileAcceptedFlag || fileAcceptedW9Flag || fileAcceptedVideoFlag;
The below updates include an errors variable to hold the errors and returning only once at the end and alerting the errors if they exist. For testing I entered in values for the file names and commented out resetting of the input values.
function fileValidation() {
const realFileBtn = document.getElementById("real-file");
const realFileW9 = document.getElementById("real-file-w9");
const realFileVideo = document.getElementById("real-file-video");
let filePathWinnerPhoto = "test.jp1g";
let filePathW9 = "test.jpxg";
let filePathVideo = "test.mov";
let imgreg = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let videoreg = /(\.mp4|\.mov)$/i;
let errors = [];
if(!imgreg.exec(filePathWinnerPhoto)){
errors.push("Winner Photo is not valid");
//realFileBtn.value = "";
}
if(!imgreg.exec(filePathW9)){
errors.push("W9 Photo is not valid");
//realFileW9.value = "";
}
if(!videoreg.exec(filePathVideo)){
errors.push("Video is not valid");
//realFileVideo.value = "";
}
if(errors.length > 0){
alert(errors.join("\n"));
}
return (errors.length == 0);
}
fileValidation();

Pass Array as a parameter in Javascript

This function is used to check if the checkbox is selected or not.Can somebody help how to pass the array as a parameter to URL which will call a stored procedure.
function js_remove_masters(theForm) {
var vCheckedCount = 0;
var vContinue = true;
var mycheckedarr = [];
var myuncheckedarr = [];
//check to see if anything is selected
if ((theForm.selected.length == null) && (!(theForm.selected.checked))) {
vContinue = false;
alert("Please select an item to be deleted.");
} else if (theForm.selected.length != null) {
for (var i = 0; i < theForm.selected.length; i++) {
if (theForm.selected[i].checked) {
vCheckedCount = 1;
mycheckedarr.push = theForm.selected[i].value;
} else {
myuncheckedarr.push = theForm.selected[i].value;
}
}
if (vCheckedCount == 0) {
vContinue = false;
alert("Please select an item to be deleted.");
}
}
if (vContinue) {
theForm.action = ("library_search_pkg_nv1.remove_checkin_masters");
-- - here how to pass array parameters
theForm.submit();
}
}
procedure remove_masters(
masterID in smallarray
default smallempty,
masterIDunselected in smallarray
default smallempty
);
Just get rid of the JavaScript entirely. You are submitting the form.
If a checkbox is checked then its name/value pair will be included in the form data.
If it isn't checked, then it won't be.
If you have a bunch of checkboxes (or other elements) with the same name, then most server side form data parsing libraries will express that as an array automatically. The main exception is PHP which requires that you put [] on the end of the name first.

Check for duplicate name before adding in the dropdown

I have two issues:
I want user to add the values in the dropdown but before that I am checking if the value is already present in that using this function:
function IsNameAlreadyPresent(List,Name){
$.each($("'#'+List option"),function(i,e){
if(e.innerHTML == Name){
return true;
}
});
}
function AddOptionName() {
var Name = $("#txtName").val();
if(IsNameAlreadyPresent(List,Name)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
}
else{
AddNewOption(Name);
}
}
I want to use this same function many times in my code to check whether the value entered is unique or not by passing the id of the dropdown and the name to be entered. but somehow this doesnt work.
how to pass the id as a parameter ($("'#'+List option")?
I am using the same function to edit the text of the option as well. but somehow if the user clicks edit and he doesnt want to change the text and clicks OK it gives an alert that the option is already present.
The option is only once including the one open in the popup. how to check this ?
var x = document.getElementById("List");
var l_sName = x.options[x.selectedIndex].text;
$("#List option[value="+l_sName+"]").remove();
Your selector is wrong, it should be $("#"+List+" option"). Also return inside $.each() will not return from your function, but break $.each() if false. Change your IsNameAlreadyPresent(List,Name) to this:
function IsNameAlreadyPresent(List, Name) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name) {
result = true;
return false;
}
});
return result;
}
For this part you can add a name to be excluded for checking, for example:
function IsNameAlreadyPresent(List, Name, Excluded) {
var result = false;
$.each($("#"+List+" option"), function (i, e) {
if (e.innerHTML == Name && e.innerHTML != Excluded) {
result = true;
return false;
}
});
return result;
}
function AddOptionName(Excluded = "") {
var Name = $("#txtName").val();
if (IsNameAlreadyPresent(List, Name, Excluded)) {
alert("Name \"" + Name + "\" already exists. \nPlease type an unique name.")
} else {
AddNewOption(Name);
}
}
and then call it with AddOptionName( $("#"+List+" option:selected").html() );

Refactor javascript function

:) i have created some javascript, it works well, my javascript knowledge limit me to create some compact and light script.
this is some sub menu javascript of aspx framework, here it it the script :
if (name === 'diensten/consultancy')
{
activeOne();
}
else if (name === 'diensten/maatwerk')
{
activeTwo();
diesntenActive();
}
else if (name === 'diensten/outsourcing')
{
activeThree();
diesntenActive();
}
else if (name === 'diensten/opleidingen')
{
activeFour();
diesntenActive();
}
else if (name === 'diensten/implementaties')
{
activeFive();
diesntenActive();
}
else if (name === 'support')
{
activeOne();
supportActive();
}
else if (name === 'support/contact')
{
activeTwo();
supportActive();
}
else if (name === 'support/download')
{
activeThree();
supportActive();
}
else if (name === 'overOns')
{
activeOne();
overOnsActive()
}
else if (name === 'overOns/cebes')
{
activeTwo();
overOnsActive()
}
else if (name === 'overOns/partner')
{
activeThree();
overOnsActive();
}
else if (name === 'overOns/vacatures')
{
activeFour();
overOnsActive();
}
else if (name === 'fireman')
{
productenActive();
}
else if (name === 'prio')
{
productenActive();
}
else if (name === 'firstwatch')
{
productenActive();
}
else if (name === 'firstwatchOnline')
{
productenActive();
}
else if (name === 'cebesFrame')
{
productenActive();
}
else if (name === 'cms')
{
productenActive();
}
return false
I am sure there is a way to shorten this javascript, not too urgent, just for give me more knowledge about javascript. Any suggestion are welcome. Thanks.
A start would be to use a switch statement instead of a long if/else tree.
switch (name) {
case 'diensten/consultancy':
activeOne ();
break;
case 'diensten/maatwerk':
activeTwo ();
diesntenActive ();
break;
...
case 'cms':
productActive ();
break;
default:
console.log ("No handler found for '" + name + "'!");
}
An alternative method is to use an objectin which you define functions and associate them to relevant keys.
var func_map = {
'diensten/consultancy': function () {
activeOne ();
},
'diensten/maatwerk': function () {
activeTwo ();
diesntenActive ();
},
'diensten/outsourcing': function () {
activeThree();
diesntenActive();
},
...
'cms': function () {
productenActive();
}
};
if (name in func_map) func_map[name] ();
else console.log ("No handler found for name = '" + name + "'!");
You have a perfect situation for a lookup table. You have a whole bunch of possibilities for the name and your action for each name is just one or more simple function calls.
That means you can use a lookup table. You put the value for name as the key and an array of function names to call for that name. One lookup in the table gets you an array of functions to call and you loop through the array to call each one. This has the advantage that to add more items, you just add a new line to the table without writing any additional lines of code:
var lookup = {
"cms": [productenActive],
"cebesFrame": [productenActive],
"firstWatchOnline": [productenActive],
"fireman": [productenActive],
"firstwatch": [productenActive],
"prio": [productenActive],
"overOns/vacatures": [activeFour, overOnsActive],
"overOns/partner": [activeThree, overOnsActive],
"overOns/cebes": [activeTwo, overOnsActive],
"overOns": [activeOne, overOnsActive],
"support/download": [activeThree, supportActive],
"support/contact": [activeTwo, supportActive],
"support": [activeOne, supportActive],
"diensten/implementaties": [activeFive, diesntenActive],
"diensten/opleidingen": [activeFour, dienstenActive],
"dienstenout/outsourcing": [activeThree, dienstenActive],
"diensten/maatwerk": [activeTwo, dienstenActive],
"diensten/consultancy": [activeOne]
};
var fns = lookup[name];
if (fns) {
for (var i = 0; i < fns.length; i++) {
fns[i]();
}
}
Here's my attempt. Its not the best in that its very specialized to your case. However, it does provide a lot of dynamic calling and code reuse.
var subPage = {
'diensten' : ['consultancy', 'maatwerk', 'outsourcing', 'opleidingen', 'implementaties'],
'support' : [undefined, 'contact', 'download'],
'overOns' : [undefined, 'cebes', 'partner', 'vacatures'],
}
var others = ['fireman', 'prio', 'firstwatch', 'firstwatchOnline', 'cebesFrame', 'cms'];
var active = [activeOne, activeTwo, activeThree, activeFour, activeFive];
var addr = name.split('/');
if (subPage[addr[0]]){
var index = subPage[addr[0]].indexOf(addr[1]);
if (index != -1){
active[index]();
if (addr[1] !== 'consultancy') // Special case
this[adder[0]+'Active'](); // Assuming this refers to the scope where diesntenActive() lives
}
} else if (others.indexOf(addr[0]) != -1){
productenActive();
}
return false;
Anyways, this probably over-complicates things. I would still recommend you either use a switch statement or a lookup table, unless you really really care about reducing your script size. Only in that case might you consider my very specialized approach.

Categories

Resources