'Passing JavaScript function parameters to jQuery
I am working on some legacy code. For the first phase of refactoring, I'm updating all the scripts to jQuery, because they're inconsistently switching between vanilla JS and jQuery. Everything has been easy to convert. However, I'm having issues trying to figure out how to get parameters from a JavaScript function into a jQuery selector/function.
For context, the original authors wrote this generic JS function:
// Submits the specified form and command.
function globalSubmitForm(formName, elementName, commandText) {
document.getElementById(elementName).value = commandText;
document.getElementById(formName).submit();
}
I rewrote the function as:
function globalSubmitForm(formName, elementName, commandText) {
$('#elementName').attr('value', 'commandText');
$('#formName').submit();
}
However, as I'm sure you will already see, the jQuery selector and functions are reading the text verbatim, not referencing the function parameters.
I haven't tried much experimenting. I'm still new to JavaScript and jQuery and have just been living inside the jQuery documentation for much of my refactoring. However, I have not been able to find any documentation or answers.
The one thing I have tried is this:
$('#' + elementName).attr('value', commandText);
$('#' + formName).submit();
However, I am not at a point where I can test this quite yet. My IDE (PhpStorm 2021.3) no longer inspects that the JS function parameters are unused, but I feel as though there might be a better way to write this.
I think that removing the quotes from commandText will work correctly as the expected argument is a string. But concatenating the parameters in the jQuery selector feels clunky and does not sit well with me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
