2

I'm a bloody beginner at this,so please don't judge me,ok? So I made a Website with this text field:

Text: <input type="text" name="text" value="" id="input1"/>

And I made a button,used to get the input of the Text field:

<input type="submit" onclick=getinput>

and this is the getinput()-function:

<script>
   function getinput(){
     const val = document.querySelector('input1').value;
     console.log(val);
     console.log("No error in function implement.");
   }
</script>

but I generated the following error:

VM195:3 Uncaught TypeError: Cannot read properties of null (reading 'value')
    at <anonymous>:3:45

I don't know what this error means,and how to fix it,could someone please help me?

2 Answers 2

1

You have some small mistake / bugs in your code. i refeactor it.

1.) the querySelector was wrong. For Ids use '#slectorName'.

2.) onclick="getinput()" instead onclick=getinput

function getinput(){
    const val = document.querySelector('#input1').value;
    console.log(val);
    console.log("No error in function implement.");
}
<input type="text" name="text" value="" id="input1"/>

<input type="submit" onclick="getinput()">

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

Comments

1

The problem is with the selector. To select an id with document.querySelector, you have to prefix it with a hashtag. Like:

function getinput(){
  const val = document.querySelector('#input1').value;
  console.log(val);
  console.log("No error in function implement.");
}

Alternatively, you can use document.getElementById. For example:

function getinput(){
  const val = document.getElementById('input1').value;
  console.log(val);
  console.log("No error in function implement.");
}

Also, in the submit button, you have to wrap the attribute value in double quotes. You have to write this:

<input type="submit" onclick="getinput()">

instead of this:

<input type="submit" onclick=getinput>

Comments

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.