0

HTML:

<form>
   <input type="text" id = "userText"/>
   <button onclick="getData()">Send</button>
</form>

Javascript:

  var inputUser;
  // I tried this and it didn't work either

  function getData(){
    inputUser = document.getElementById("userText").value;
    alert(inputUser);
  }

  $(window).load(
    function(){ * something * })

I can get data in function getData() but can't access that data into $(window).load(function()).

If I put document.getElementById() or try to use inputUser in * something * code. It's return nothing. I want use the text input from user in * something *.

So how can i do this? Thanks!

Minh Huy
  • 41
  • 6
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Randy Casburn Mar 07 '19 at 15:35
  • You should try using `$(document).load` while making sure `getData` is available in scope. Also when you do Window.load, the input field is not available and getData is not available too. – nircraft Mar 07 '19 at 15:36
  • "_It's return nothing_" Nope, unless an error occur, it returns an empty string, that's something. – Teemu Mar 07 '19 at 15:38
  • I tried init ```var inputUser``` outside getData function and it's didn't work too. *It's return nothing* is acutally return ```undefined```. – Minh Huy Mar 07 '19 at 15:46

2 Answers2

2

The load event fires at the moment when the user has loaded the document.

At that point, the user hasn't typed anything into the form.

You can't get the text input in that function because it doesn't exist yet.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I agree with you at this point. So how can I use the text input from user without delete the $window.load() ? – Minh Huy Mar 07 '19 at 15:47
  • Why do you want to keep `$window.load() `? It sounds like a solution looking for a problem rather than the other way around. Solve your actual problem instead. – Quentin Mar 07 '19 at 15:51
  • I don't know why but when i delete $window.load(), my google map disappear – Minh Huy Mar 07 '19 at 15:54
  • 3
    What Google Map? Maybe you should ask a new question about your actual problem with an [mcve]. – Quentin Mar 07 '19 at 15:57
  • Thank you so much! I asked a new question [here](https://stackoverflow.com/questions/55048256/google-map-disappear-when-delete-window-load) – Minh Huy Mar 07 '19 at 16:12
1

You declared var inputUser inside getData(), therefore you can only access it inside getData() (it's called a scope).

Declare it outside (just above) with var inputUser;. Then, inside getData() just set it with inputUser = ... (without another var) and then you can access it from $(window).load.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63