0

I am trying to retrieve a text input from an input field using html and js.

HTML

<div class="inputarea">
        <input type="text" value ='' id='myInput' placeholder="What do I need to do?"> 
        <button onclick='todolist().submit()'>SUBMIT</button>
</div>

JS

function todolist(){
    function first(){
        window.open("todolist.html")
    }
    function submit(){
        var userinput = document.getElementById('myInput').value;
        console.log(userinput);
    }
}

When I press submit the console says "Uncaught TypeError: Cannot read property 'submit' of undefined"

Any help would be much appreciated.

Sam.

3
  • 1
    did you import your js file in the html? Commented Mar 24, 2020 at 15:33
  • Because todolist returns undefined. That is not how classes work in JavaScript Commented Mar 24, 2020 at 15:37
  • @Mox in that case todolist would be undefined Commented Mar 24, 2020 at 15:37

2 Answers 2

3

Try returning the functions

function todolist() {
  function first() {
    window.open("todolist.html")
  }

  function submit() {
    var userinput = document.getElementById('myInput').value;
    console.log(userinput);
  }
  return {first, submit};
}
<div class="inputarea">
  <input type="text" value='' id='myInput' placeholder="What do I need to do?">
  <button onclick='todolist().submit()'>SUBMIT</button>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

Probably todolist should be class (EcmaScript 6+). Or you ment to return object from todolist function:

function todolist(){
  return {
     first(){
        window.open("todolist.html")
    },
     submit(){
        var userinput = document.getElementById('myInput').value;
        console.log(userinput);
    } 
  }
}

todolist().submit();

2 Comments

Ok ill put it into a class
@SamuelWash, Note that not every browser supports ES6 class syntax. You may need some tool like Babel to make it work on browsers like Internet Explorer. Check this out: caniuse.com/#feat=es6-class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.