How do I make a script more useful?

I’m at day three of learning JS using Safari.
I’ve written a few scripts which do what I want, but I would like to make them more portable or useful.
eg:

 function myFunction() {
   var vtext;
   vtext = document.getElementById("ACName").value;
   document.getElementById("ACName").value = vtext.toUpperCase();
   }

This works perfectly fine for the form field ACName when called by;
onchange = "myFunction();"

But I would like to be able to capitalise the content of any field with a script call but do not yet have this skill.

Can a script accept parameters, one of them being the elementID to operate upon?

What must I change in this script (and/or call to it) to achieve that?

Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://freecodecamp.org.

To answer your question without just giving you the solution, you can pass arguments to a function like:

function myFunc(someValue) {
  console.log(someValue);
}

someValue is a parameter for the myFunc function above. You can pass a value outside the function like:

myFunc('a value');  // will display 'a value' to the console.

Happy coding :slight_smile:

3 Likes

But I would like to be able to capitalise the content of any field with a script call but do not yet have this skill.

function myFunction(field){
   const container = document.querySelector(field);
   const oldContent = container.innerHTML;
   container.innerHTML = oldContent[0].toUpperCase() + oldContent.slice(1);
}
1 Like