Merge or extend JavaScript functions

Viewed 34

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;
}
3 Answers

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