Requesting help with code integration

Hello and good day.

I am working on a website that needs to have a dropdown selector to change the degrees from Celsius to Fahrenheit and I’m having trouble integrating it with PyScript. I have attached an image of a mockup for the code minus exporting the result to a table. Is it possible that anyone could help me find a solution or at least an alternative to the issue?

Hello, and welcome to the PyScript forum! There’s a few issues here - I know you’ve included just a portion of your code; please feel free to ignore any tips that aren’t relevant in the context of the full code:

  • Instead of onclick, you’ll want to use the py-click attribute to execute Python code in response to a click event. (This pattern extends to other event types as well - py-mouseover, py-ipnut, etc).
  • You’ll need to get the value of the input element and do your calculations on that, not the element itself: num1 = document.getElementById('in').value, and similarly, if document.getElementById("dd").value == 'cel':
  • The lines (float(num1)) * 9/5 - 32 and (float(num1)) * 59 + 32 don’t actually do anything, or change the value of num1. You’ll want to either return that whole expression, or assign it to a variable and return that, as in the example below.
  • I think you know this, but for completeness, you’ll need to from js import document or similar to use the document object

A working example follows. I have this function print out the result, just to show that it’s working, but of course you could remove the print statement for your purposes.

<input type="text" id="in">
<select id="dd">
    <option value="cel">Celcius</option>
    <option value="far">Fahrenheit</option>
</select>
<button id="submit-button" type="submit" py-click="myFunction()">OK</button>
<textarea id="result-textbox" cols="30" rows="10"></textarea>

<py-script>
    from js import document
    from pyscript import when

    def myFunction():
        num1 = document.getElementById('in').value
        if document.getElementById("dd").value == 'cel':
            result = float(num1) * 9/5 - 32
        else:
            result = float(num1) * 5/9 + 32

        print(result)
        return(result)
</py-script>