如何根据文本输入中输入的命令在表单提交上执行JS函数



当输入特定文本以触发事件时,我如何采用此表单并执行某些函数?

<form id="form">
<input type="text" placeholder="Enter Command" id="text" />
<input type="button" value="Submit" id="submit" />
</form>
function RUN() {
// when run is entered in text field this function is exe
}
function CLOSE() {
// when close is entered in text field this function is exe
}

示例命令:RUN和CLOSE

编辑一些我有点工作的东西:

如何使多个命令执行不同的函数?这在不添加第二个或第三个命令的情况下有效。一旦我添加了多个,唯一有效的就是底部的那个。

function readCommand() {
let readInput = document.querySelector('#SearchBar').value
//           ↓ no .value, it's already here -----------↑
if (readInput === 'RUN') {
//             ↑ === vs =
CMDRUN()
} else {
alert(`Not a command`);
}
}
function readCommand() {
let readInput = document.querySelector('#SearchBar').value
//           ↓ no .value, it's already here -----------↑
if (readInput === 'CLOSE') {
//             ↑ === vs =
CMDCLOSE()
} else {
alert(`Not a command`);
}
}
function CMDRUN() {
alert ("This is an alert dialog box 1");  
}
function CMDCLOSE() {
alert ("This is an alert dialog box 2");  
}

这可以通过使用onsubmit事件和窗口对象来完成,以便使用字符串输入调用函数。

提交表单时,输入框的值就是将要执行的函数。

document.getElementById("form").onsubmit = function() {
window[document.getElementById("text").value]();
}
function RUN() {
// when run is entered in text field this function is exe
}
function CLOSE() {
// when close is entered in text field this function is exe
}
<form id="form" action="">
<input type="text" placeholder="Enter Command" id="text" />
<input type="submit" value="Submit" id="submit" />
</form>

function readCommand() {
let readInput = document.querySelector('#SearchBar').value
if (readInput === 'RUN') {
CMDRUN()
} else if (readInput === 'CLOSE') {
CMDCLOSE()
} else {
alert(`Not a command`);
}
}
function CMDRUN() {
alert ("This is an alert dialog box 1");  
}
function CMDCLOSE() {
alert ("This is an alert dialog box 2");  
}
<form name="SearchContainer" id="SearchContainer" class="WindowMenuUp">
<input type="text" placeholder="Search and Commands" name="SearchBar" id="SearchBar" class="SearchBar" />
<input type="button" value="Search" name="SearchButton" id="SearchButton" class="SearchButton" onclick="readCommand()" />
</form>

最新更新