How do I take this form and execute certain functions when a specific text is entered to trigger the event?
<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
}
example commands: RUN and CLOSE
EDIT something i got kinda working:
How do I make multiple commands exe different functions? This works without the second or third command added. Once I add multiple the only one that works is the one at the bottom.
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");
}
CodePudding user response:
This can be done using an onsubmit event along with the window object to call a function using the string input.
When the form is submitted, the value of the input box is the function that will be executed.
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>
CodePudding user response:
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" >
<input type="text" placeholder="Search and Commands" name="SearchBar" id="SearchBar" />
<input type="button" value="Search" name="SearchButton" id="SearchButton" onclick="readCommand()" />
</form>