0

I'm trying to get a variable value (account) from the user and then send it to my script. I'm using this code:

<p><input type="text" id="accountField"=>Enter Number</input>
<button onclick="test()">Submit</button></p>
<script>
    function test(){
        var getAccount = document.getElementById("accountField").value;
        console.log(getAccount);
        return getAccount;
    }
    var account = test();
</script>
<script type="text/javascript" src="test.js"></script>

The problem is that the src script runs without waiting for the user input and so it fails. I've tried the defer='defer' but that didn't make it wait.

I just need to get one number from the user and add it to my script as a variable. I was able to get it to work using the windows prompt, but I would rather avoid that if possible.

EDIT: I'm trying to make a synchronous call, not an asynchronous call. I am getting some information from a form and then making a call with that information. I don't want to call the external script unless the user answers the question in my form.

glaemart
  • 129
  • 1
  • 10
  • "I don't want to call the external script until the user answers the question in my form." — The "until" in that sentence makes the task asynchronous! – Quentin Feb 20 '18 at 22:27
  • Can you suggest a better way for me to get the variable to my script? That is my real issue. I need to pass a piece of data to my external script and I have no idea how. – glaemart Feb 20 '18 at 23:42
  • Make the content of the script a function. Call that function when you have the data. – Quentin Feb 20 '18 at 23:43
  • `var account = test();` will call the function on page load. You probably don't want this! You have the click handler on the button, leave it up to that. – Jon P Feb 21 '18 at 01:04
  • @JonP - I was trying to get the result of test out of the function and into my variable account. This is the only way I knew to get it to work. I will research other ways. Thanks! – glaemart Feb 21 '18 at 15:05
  • @Quentin It doesn't seem like you can wrap a script in a function, but I will keep trying. – glaemart Feb 21 '18 at 15:07
  • You put the code that is in the script in a function. – Quentin Feb 21 '18 at 15:21

1 Answers1

-1

You can create the element after your input has been read, no?

Something like:

var account, injected // Create the state variables

function injectScript(src) {
    const script = document.createElement('script')
    script.src = src
    document.getElementsByTagName('head')[0].appendChild(script)
    injected = true
}
function test(){
    const getAccount = document.getElementById("accountField").value

    // Probably want to do this to keep `account` up-to-date when the event handler runs
    account = getAccount
    account && !injected && injectScript('test.js')
}
test()
AP.
  • 8,082
  • 2
  • 24
  • 33