Carry the value of an input to a variable

How do i set it so that when a button is clicked, the value of an input is carried over to a variable?
Basically, like, a variable is set to the value of an input.

It’s quite easy to do this, try:

document.querySelector('#btn').onclick = function () { // let's say the value of the input element is five
alert(document.querySelector('input').value) // this will get it onclick! which would alert 5!
}

And change your code to the correct values ya have

2 Likes

i get this error message:
Uncaught TypeError: Cannot read property ‘value’ of null

Most likely you have more than one <input> element so querySelector gets confused. Based on experimentation it looks it returns the first element it finds

Yeah, try doing like #idhere

Or even better do:

var x = document.querySelector('input').value;
x[0] // returns teh first one

I only have one input tag

No issues on my end

This post was flagged by the community and is temporarily hidden.

That will only return the first character of the value of the input so it is incorrect
oh and also querySelectorAll seems to return an array

I can’t seem to find the project.

@lankybox10 did ya archive it?

@LankyBox01

Here are some resources that can help you:


3 Likes