Can't pass an input value into a javascript variable

Can't pass an input value into a javascript variable
0.0 0

#1

Hello everyone,

I have been stuck for one day on this script. I am trying to pass an input value into a variable, but for some reason my code doesn’t work. I saw other solution online to pass value into a variable, but I would like to understand why what I’m writing doesn’t work.

Thank you for your help!

HTML:

<input id = "search" placeholder="Search for..."></input>
<button value = 'send' id = "submit" onclick="myFunction()">Search</button>

<div class = "alpha"></div>

JAVASCRIPT:

function myFunction() {
var test = document.getElementById("search").value;
}

console.log(test);

If I wrote a jquery within the function like this one:

$(’.alpha’).html(document.getElementById(“search”).value);

it will work. But I still can’t assign it to a variable!

Thank you for your help!


#2

It’s easier to get help if you can post your full project, either your repository or Codepen.

Your vanilla JS code works fine, but you aren’t seeing the value because console.log is not running in the same context as the variable text, and at a totally different time. You need to put it in myFunction to see your value:

function myFunction() {
  var test = document.getElementById("search").value;
  console.log(test)
}

#3

My god! Thank you! It just had to be within the function… But how can I access the variable outside of the function? All the code should happen within this function now?

I am working on a Wikipedia viewer, but first I wanted to see how I can store an input value into a variable to then use it with the API.

Thanks again for your help!


#4

If your code is writing to and depending on variables outside of the functions that do your heavy lifting, you’re in for a world of hurt. You should absolutely make your AJAX call in your button’s click handler. I blather almost without end on the topic in another post (good stuff starts in the second section).


#5

Thanks for the tip :wink: it will probably save me from more headaches like I had yesterday! haha