0

I am trying to set up my index page so that each stock in the user's portfolio has buttons to buy and sell said stock.

The first step is working so far. Each row in the index table has buy and sell buttons. Upon clicking, for example the "buy" button on the row corresponding to the user's TSLA holdings, the user will then be taken to the "/buy" page, but with a query attached to the URL so it looks like this:

http://e598dc89-7244-4c42-a746-34ca822c70e2-ide.cs50.xyz/buy?buy_TSLA=

What I want to do with the buy page is now have a script autofill the stock symbol form with the query value, in this case TSLA. I'm currently attempting to implement with the following javascript file:

function fill_buy()
{
    var x = location.search;
    var formFill = document.getElementByID("symbol");
    formFill = x;

}

Then adding a reference to the script in the header of layout.html:

<script src="fill_buy.js"></script>

Then calling the script in the body of buy.html:

{% block main %}
    <h1>Buy Stock</h1>
    <h2>Your buying power: {{ userCash }}</h2>
    <script>fill_buy();</script>
    <form action="/buy" method="post">
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="Symbol" type="text">
        </div>
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="shares" placeholder="Shares" type="text">
        </div>
        <button class="btn btn-primary" type="submit">Buy</button>
    </form>
{% endblock %}

However, it doesn't seem to be working. The /buy page loads up normally, and in the inspector console I get the following error: ReferenceError: fill_buy is not defined

Any ideas? I feel like I'm close, but just can't connect the last dot with all this. Thanks in advance!

0

1 Answer 1

0

Is the js file being loaded at all? Any warnings in console like "file not found"? According to flask doc, js files should be in static (sub)directory and called with url_for.

But wait there's more! (from comments)

The pseudocode for this script:

  1. get the query string
  2. get the symbol element
  3. set the symbol element to the query string.

There are some bits missing. It should be more like:

  1. get the query string
  2. parse the query string (you may find javascript api URLSearchParams of interest)
  3. Set the value of the symbol element to the passed parameter.

The query string ?buy_TSLA= doesn't look right. It should be something like ?buy=TSLA.

2
  • thanks! This fixed the first problem. Now I'm not getting that error, but my script just straight up isn't working. I think at this point it's a javascript problem, not a HTML problem Commented Nov 5, 2020 at 20:57
  • answer amended. Commented Nov 6, 2020 at 12:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .