Skip to content

update a HTML input field with the data coming from a external Javascript Websocket

I am new to JavaScript, not sure if this very basic question. I’ve created a Bitcoin Price update dashboard using the data fetched from the external WebSocket. I managed to get the data from the WebSocket and display it on the console tab and display the data in a h1 tag. The price updates every seconds. Now i need to show the price in a html field. i tried but it’s kinda hard for me.

I have provided the code snippets below as well as external Websocket from where I am pulling the data.

Please let me know how should I insert the row dynamically into a HTML input field. Thank you so much in advance

                                <input type="text" class="form-control" id="btcpricenow" readonly>
                                  <script>
                                      
                         var priceSocket = new WebSocket("wss://stream.binance.com:9443/ws/[email protected]"),
                          liveprice = document.getElementById("btcpricenow");
                          priceSocket.onmessage = function (event) {
                           var liveprice = JSON.parse(event.data);
                           liveprice.innerText = parseFloat(liveprice.p).toFixed(2);
                          }
                                  </script>

Answer

You set liveprice to be the HTML element, and then reset it inside your function to be the parsed event.data. Don’t reset the variable like that, just set a new variable instead. Also, when you are putting a value inside an input element use value, not innerHTML

<input type="text" class="form-control" id="btcpricenow" readonly>
<script>
  let priceSocket = new WebSocket("wss://stream.binance.com:9443/ws/[email protected]"),
    liveprice = document.getElementById("btcpricenow");
  priceSocket.onmessage = function(event) {
    let data = JSON.parse(event.data);
    liveprice.value = parseFloat(data.p).toFixed(2);
  }
</script>