htmlpyscript

I want to take the input value from an HTML input block using PyScript, but it doesn't work. Why?


I am trying to use PyScript in my HTML projects, since I'm more fluent in it than JavaScript. I need to pull input from an input block, but what should work doesn't seem like it does.

When the user presses the submit button, it's supposed to change the words above it to the value of the input box. However, the code only returns "None", as if the value doesn't exist.
HTML code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>PyScript Template</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
        - paths:
            - /demo.py
    </py-env>
</head>

<body style="font-family:Times New Roman;margin-left:40px">

    <br>
    <p id=main_description class=text>
        Hello, world.
    </p>

    <input class=player_input type=text id=input_box name=input autocomplete=off placeholder="What will you do?">
    <button type=button id=submit pys-onclick=submit_input>submit</button>

    <py-script src=/demo.py></py-script>
</body>

</html>

PyScript code:

# demo.py

def submit_input(e):
    input_box = Element("input_box")
    player_input = input_box.select(".value")
    main_description = Element("main_description")
    main_description.write(player_input)

I have searched for a solution to this everywhere, but it looks like PyScript is still relatively new, so I couldn't find anything except traditional Python solutions. Any advice would be greatly appreciated.


Solution

  • On this line player_input = input_box.select(".value") you are trying to access an element with a class of value but no elements exist inside the input. To retrieve the value of the input you need to access it with the value property like so:

    # demo.py
    
    def submit_input(e):
        input_box = Element("input_box")
        player_input = input_box.value
        main_description = Element("main_description")
        main_description.write(player_input)