1

I did a bunch of buttons on a navbar. These buttons can trigger different articles or lesson in two languages from side to side.

Later, I found that this is troublesome when I try to search for a specific article. So I decided that I'll add an input text bar to take my input and trigger a javascript function that I want.

I simplified the numbers in this post, but this is the core of the script. I named the functions with 4 digits numbers MMDD so I wish that I can type in a box 0312 and the function 0312 get executed.

However, I cannot seem to get it to work. Is that even possible in javascrip? If not what approach do you recommend?

function fr01() {
  document.getElementById("fr01").innerHTML = "text here will appear in french"
}

function en01() {
  document.getElementById("en01").innerHTML = "text here will apear in english"
}

function myFunction01() {
  fr01();
  en01();
}

function myFunction() {
  var x = document.getElementById("myInput").value;

  function 'x'
}
<input type="text" id="myInput" oninput="myFunction()">
<button onclick="myFunction01()">CHAPTER01</button>

the top part works perfectly fine and in realtime, when I press the corresponding button it shows both sides, when I try to type in number I get this error message

myFunction is not defined at HTMLInputElement.oninput

Didn't I already define it in the top portion?

Thank you for taking the time to read this.

3
  • 1
    What do you expect function 'x' to do? Commented Mar 27, 2021 at 10:44
  • remove the function 'x' and it works ok Commented Mar 27, 2021 at 10:49
  • I now believe I forgot to add to it' myFunction'x' I want to assign a function that has a variable name which is based on the input I give it Commented Mar 27, 2021 at 10:56

1 Answer 1

1

Do call functions dynamically based on for example a text value, then you could create a map which connects a string to a function. An object is very similar to this. It has properties, which can be strings, and a value, which can be functions.

const actions = {
  'foo': function() {
    // Do something.
  }
};

With this pattern you can create a list of valid options and the connect the corresponding functions that come with the list.

Now let's say you have a string. With that string you can select a function from the object with the bracket notation.

const string = 'foo';
const action = actions[action]; 

If a value is found, then action will now be a function. Otherwise it will be undefined.

The snippet below demonstrates this principle.

function omg() {
  console.log('omg');
}

function bark() {
  console.log('bark');
}

const actions = {
 '0312': function() { // Regular function.
   console.log('Hello')
 },
 '0420': () => { // Arrow function.
   console.log('Wow')
 },
 '1360': () => console.log('Vroom'), // Arrow function variation.
 '1337': () => { // Arrow function that calls two other functions.
   omg();
   bark();
 },
 '7331': [omg, bark] // Array with function references.
};

const form = document.querySelector('#form');
const actionField = document.querySelector('#action');

form.addEventListener('submit', event => {
  const selector = actionField.value;
  const action = actions[selector];
  
  if (typeof action === 'function') {
    action();
  }
  
  if (Array.isArray(action)) {
    action.forEach(subAction => {
      subAction()
    });
  }
  
  event.preventDefault();
});
<form id="form">
  <label for="action">Try me (0312, 0420, 1360 and 1337 will work)</label>
  <input type="text" id="action" />
  <button type="submit">Execute</button>
</form>

Sign up to request clarification or add additional context in comments.

5 Comments

Now theoretically, can this trigger two functions? or since because I have the two functions in a parent function it wouldn't matter? Thanks a lot btw!
Well, it could, if you would have an array of functions and loop over the array and call each function. Or, like you said, use a single function to call two, or more, other functions.
instead of the console.log(''), can I write a function?
Yes you definitely can, it already are functions. I've added some more variations on how to write them down () => {} is basically the same as doing function() {}, but with some minor differences. You could write anything you want the function to do inside the brackets {}.
Uncaught SyntaxError: Unexpected token ',' there is a bug there somewhere in my code, but I'll find it. I think your code is exactly what I am looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.