I am trying to make my own bootleg bash clone in JS and PHP, but I am stuck on a problem. When trying to execute this script, error log tells me that enteredCommand() is not defined, even though you can see it being above the form.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
if($(".command") !== null){
function enteredCommand(){
}
} else{
// do nothing
}
});
</script>
<form id="commandField" onsubmit="return enteredCommand();">
<p>bbash~ User:</p>
<input type=text>
</form>
Please help! I am new. This is not a duplicate, since I don't see how it can't be defined. And yes, the console specifies that the error happens at "onsubmit".
CodePudding user response:
It's because you've defined the enteredCommand()
function out of scope of the onsubmit
invocation.
You need to invert the logic so that the if
condition is within the enteredCommand()
function. Also note the use of an unobtrusive event handler in the JS code. Adding onX
attributes to HTML is no longer good practice and should be avoided.
Finally, to retrieve a value from a jQuery object you need to call val()
. Comparing a jQuery object to null
will never be true, as a jQuery object is never null.
let execCommand = c => {
console.log(`User entered '${c}', handle it here...`);
}
$(function() {
let $command = $('.command');
$('#commandForm').on('submit', e => {
e.preventDefault(); // stop the form submission so you can handle it manually
let command = $command.val().trim();
if (command)
execCommand(command);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form id="commandForm">
<p>bbash~ User:</p>
<input type="text" />
</form>