I am trying to get the values of several input fields and then displaying those values somewhere else on the page using JS functions. I will have 10 input fields, therefore is there a way I can optimize my JS code and write a function to loop through the values of the input fields and display them afterwards? Here are two functions which I wrote for two different fields:
function gotoTask() {
var message = document.getElementById("goto").value;
goto_message.innerHTML = message;
}
function waitTask() {
var message = document.getElementById("wait").value;
wait_message.innerHTML = message;
}
You could write a curry/factory function:
function createTaskFn(el, messageElId) {
return function() {
var message = document.getElementById(messageElId).value;
el.innerHTML = message;
};
}
var gotoTask = crateTaskFn(goto_message, 'goto');
var waitTask = crateTaskFn(wait_message, 'wait');
Give same class to your all inputs , then select them by let inputArr = document.getElementsByClassName('inputsClass') , then loop through inputArr and display their values.
You could store all the ids in an array like so
const inputIds = ['goto', 'wait', ...]
Then you can iterate over that array and call your method like so
inputIds.forEach((id) => {
const message = document.getElementById(id).value;
document.getElementById(`${id}_message`).innerHTML = message;
})
Disadvantage of my implementation: Your ids of the message fields have to have the same structure [id]_message
Related
I have a scenario where I am passing an array of objects to a function in nodejs, but the same is failing with undefined error.
Here is what I have tried :
var object = issues.issues //json data
var outarr=[];
for(var key in object){
outarr.push(object[key].key)
}
console.log(outarr) // array is formed like this : ['a','b','c','d','e']
for(var i =0; i<outarr.length;i++){
jira.findIssue(outarr[i]) //here I am trying to pass the array objects into the loop one by one
.then(function(issue) {
var issue_number = issue.key
var ape = issue.fields.customfield_11442[0].value
var description = issue.fields.summary
var ice = issue.fields.customfield_15890[0].value
var vice = issue.fields.customfield_15891.value
var sor = issue.fields.labels
if (sor.indexOf("testcng") > -1) {
var val = 'yes'
} else {
var val = 'yes'
}
var obj = {};
obj['ape_n'] = ape;
obj['description_n'] = description;
obj['ice_n'] = ice;
obj['vice_n'] = vice;
obj['sor_n'] = val;
var out = {}
var key = item;
out[key] = [];
out[key].push(obj);
console.log(out)
} })
.catch(function(err) {
console.error(err);
});
});
What I am trying to achieve : I want to pass the array values as a parameter which is required by jira.findissue(bassically passing the issue number) one by one and which should again fetch the values and give a combine json output.
How can I pass this array values one by one in this function and also run jira.findissue in loop.
Any help will be great !! :-)
I have taken a look at the code in your question.
To be honest the code you wrote is messy and contains some simple syntax errors.
A good tip is to use a linter to avoid those mistakes.
More info about linters here: https://www.codereadability.com/what-are-javascript-linters/
To output all results in one array you have to define the array outside the scope of the loop.
I cleaned the code a bit up and use some es6 features. I don't know the context of the code but this is what I can make off it:
//map every value the key to outarr
let outarr = issues.issues.map( elm => elm.key);
//Output defined outside the scope of the loop
let output = [];
//looping outarr
outarr.forEach( el => {
jira.findIssue(el).then(issue => {
//creating the issue object
let obj = {
ape_n: issue.fields.customfield_11442[0].value,
description_n: issue.fields.summary,
ice_n: issue.fields.customfield_15890[0].value,
vice_n: issue.fields.customfield_15891.value,
sor_n: issue.fields.labels.indexOf("testcng") > -1 ? "yes" : "yes",
};
//pushing to the output
output[issue.key] = obj;
}).catch(err => {
console.log(err);
});
});
//ouputing the output
console.log(output);
Some more info about es6 features: https://webapplog.com/es6/
I'm trying to turn an option from a select list into text to then use the text in a function that returns a message topic for Firebase. I have had to use a function to get the text out of the list correctly but I don't know how to then output the text from the function in the second function to be used for the messaging. I can console.log the text, but I don't know what to use to just output the text itself inside the message function. I may be confusing myself a little. Please note: There are const being declared that are being used later on so any comment of "Why are you declaring those consts" won't be helpful. I need to know what to put in the TWO ### WHAT GOES HERE ### blocks to make this work?
I have tried just using jquery's text() to simply output the data I want but that just brings back undefined every time. The only way I've been able to actually get the option text is to place it in a function, but I have to actually DO something with it and I'm not sure what function will give me my desired results.
Here is the code
const select = $("#schoolSelect");
selectedOption = function() {
### WHAT GOES HERE? ###($("#schoolSelect option:selected").text())
}
const stage2 = $("#stage2Div");
const stage3 = $("#stage3Div");
const popupClose = $("#popupClose");
const popup = $("#popup");
const selectedValues = getSelectValues(select);
// Alert Buttons Functions
// Stage 2 Button
// Sends Soft Lockdown to all devices subscribed
stage2.click(function() {
var select = $("#schoolSelect"),
selectedValues = getSelectValues(select);
if (selectedValues.length == 0) {
popup.addClass("show");
}
else if (selectedValues.length > 0) {
for (var i = 0; i < selectedValues.length; i++) {
var message = createSLMessage(
"/topics/" + ### WHAT GOES HERE? ###
)
sendMessage(message);
}
}
});
For reference, here is the jQuery that is creating the list
populateList = function() {
$.getJSON("/assets/JSON/schools.JSON", function(result) {
$.each(result, function(i){
var schools = result.schools;
var output = "";
for (var i = 0; i < schools.length; i++) {
output += "<option>" + schools[i].topic + "</option>";
}
$("#schoolSelect").html(output);
});
})
};
Here is the html of the table (though less important) for reference
<select
size="100"
multiple
id="schoolSelect"
class="school_select"
></select>
I would like the function selectedOption to actually output the text. If I place console.log where the ### WHAT GOES HERE ### tag is in the function selectedOption itself and then call the selectedOption() later, the console indeed logs the correct value from the select list. I am losing my mind a little because I know there has to be some simple way to do this I just can't seem to figure it out.
I'm a begginer in Javascript and I need to analyse a JavaScript Object generated in a loop to keep one parameter and to save this parameter for all object generated in the loop.
This is my program
var onvif = require('onvif');
var fs = require('fs');
var nombrecamera=0;
var taille=0;
var test ='';
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
var STREAM = fs.createWriteStream('STREAM.txt',{flags:'r+'});
onvif.Discovery.on('device', function(cam,rinfo,xml){
// function will be called as soon as NVT responses
nombrecamera+=1;
console.log(cam);
test += cam;
cam2= JSON.stringify({cam}, null , ' ');
//console.log(cam2);
STREAM.write(cam2);
console.log(test);
});
onvif.Discovery.probe({timeout:1000,resolve:false});
And in output in my example i've got 4 of these:
{ probeMatches:
{ probeMatch:
{ endpointReference: [Object],
types: 'tdn:NetworkVideoTransmitter',
scopes: ' onvif://www.onvif.org/type/video_encoder onvif://www.onvif.org/location/country/china onvif://www.onvif.org/type/network_video_transmitter onvif://www.onvif.org/hardware/IPC-122 onvif://www.onvif.org/Profile/Streaming onvif://www.onvif.org/name/IPC-BO',
XAddrs: 'http://192.168.1.81:10004/onvif/device_service',
metadataVersion: 1
}
}
}
And I want to keep only the XAddrs for all object generated and then put these in a json.
My first idea was to stringify this object then create a writable stream and put all json together but in this case there are no coma between the json so it doesn't create a big json with the whole data.
Thank you for your help
Jules
The easiest way to know how many addresses you have is the .length function of an array.
As I don't know whether you need a list with unique addresses or the same address can show up multiple times, I'm gonna show you both solutions.
Unique Addresses Only
function extract() {
test.forEach(cam => {
const deviceAddress = cam.probeMatches.probeMatch.XAddrs;
// only if the xaddrs is not in list yet, add it
if(test.filter(xad => xad === deviceAddress).length <= 0) {
xaddrs.push(cam.probeMatches.probeMatch.XAddrs);
}
});
// show the number of addresses
const listCount = xaddrs.length;
console.log('listCount: ', listCount);
}
No Unique Address
function extract() {
test.forEach(cam => {
xaddrs.push(cam.probeMatches.probeMatch.XAddrs);
});
// show the number of addresses
const listCount = xaddrs.length;
console.log('listCount: ', listCount);
}
Make testan array and push()the camobjects into it. Also define an array for your XAddrs-values.
var test = [];
var xaddrs = [];
// your other code
...
onvif.Discovery.on('device', function(cam,rinfo,xml){
// function will be called as soon as NVT responses
nombrecamera+=1;
console.log(cam);
// push cam object into array
test.push(cam);
cam2= JSON.stringify({cam}, null , ' ');
//console.log(cam2);
STREAM.write(cam2);
console.log(test);
});
Then extract XAddrs and push it into xaddrs array.
function extract() {
test.forEach(cam => {
xaddrs.push(cam.probeMatches.probeMatch.XAddrs);
});
// now you have an array containing only the XAddrs elements
console.log(xaddrs);
}
I'm trying to create a script on Google Adwords that changes the campaign name. But right now the script is doing nothing. What is wrong?
function main() {
var campaignIterator = AdWordsApp.campaigns()
.withCondition('Name = "teste"')
.get();
if (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var newCampaignName = 'teste2';
campaign.setName(newCampaignName);
}
}
A while loop is the most common element used after the Iterator. Try this out instead:
function main() {
var campaignIterator = AdWordsApp.campaigns()
.withCondition('Name = "teste"')
.get();
while (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var newCampaignName = 'teste2';
campaign.setName(newCampaignName);
Logger.log("Campaign Name Changed")
}
}
I have also included a "Logger.log" to display the output of the while loop. If that isn't triggering, then there is something wrong with your Iterator condition; maybe you dn't have a campaign with the name you've used.
If you wish to rename a campaign, you must provide the ID. This field can be selected using the value "Name". This field can be filtered on.
I need to convert values from one Array variable into fields of another variable in Javascript.
My variable is
field = ["entries", "body"]
and it needs to become something like
req.body.entries.body
I tried doing something like
field.forEach(function(prop){
req.body[prop] = "...";
}
but that works only on req.body.entries and req.body.body. And I need it to go all the way to req.body.entries.body
I'm doing this to get the data from a form in a document field (named entries[body]), do some cleaning up on that data, and then pass it back to node.js as if it was the request that was originally made.
UPDATE
All I need to do is to basically
exports.sanitize = function(field){
// field = ["entry","body"];
return function(req, res, next){
val = getField(req, field); // val = "Some string with data"
val = some_process(val); // some_process is a function that cleans up the string
req.body.entry.body = val; // HOW TO TAKE entry.body from the field array???
next();
}
};
As you can see, all I want is to NOT hard code entry.body but take it from field array values that passes the name of the field for processing.
If you can think of a more elegant solution to do this, please, let me know.
Thanks!
This works:
var fields = [ "field1", "field2", "field3", "field4" ];
var obj = req.body;
fields.forEach(function(prop) {
obj[prop] = {};
obj = obj[prop];
});
You want
var obj = req.body;
for (var i=0; i<fields.length-1; i++)
obj = obj[fields[i]];
var prop = fields[i];
obj[prop] = cleanUp(obj[prop]);
This will work only if req.body.entries.body is already defined:
field = ["entries","body"];
var toeval="req.body";
field.forEach(function(prop){
toeval+="."+prop;
});
toeval+="=\"...\"";
eval(toeval);
I was able to accomplish this using recursion. Hope this helps!
var foo = {
bar: {}
};
var fields = ['foobar', 'barfoo'];
function setVar (currentVar, arr, counter) {
if (arr[counter] === undefined) {
return;
}
currentVar[arr[counter]] = {};
setVar(currentVar[arr[counter]], arr, counter + 1);
}
setVar(foo.bar, fields, 0);