Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
Possible conflict while setting function between JQuery and vanilla JS?

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 class="command" 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".

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 class="command" type="text" />
</form>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!