Home > Enterprise >  Websocket data is appearing in an h1 element, but not in an input
Websocket data is appearing in an h1 element, but not in an input

Time:09-03

I am working on a Binance API project for getting the live price of Bitcoin. I wrote some Javascript code to do this.

The issue is that it is not working in an input but it is working in a h1. I need it to work in the input. How can I do this?

<h1 id="btc-price"></h1>
<input type="text" id="btc-price" value="" />
let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceElement = document.getElementById('btc-price');
let lastPrice = null;

weburl.onmessage = (event) => {
  let stockObject = JSON.parse(event.data);
  let price = parseFloat(stockObject.p).toFixed(2);
  stockPriceElement.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
  stockPriceElement.innerText = price;
  lastPrice = price;
};

CodePudding user response:

The issue is because you've created two HTML elements with the same id, which is invalid. id must be unique. In addition, the method used to update the content of an h1 and an input are different.

To set the value of the input, select it from the DOM and set its value property, like this:

let weburl = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');
let stockPriceInput = document.querySelector('#btc-price');
let lastPrice = null;

weburl.onmessage = (event) => {
  let stockObject = JSON.parse(event.data);
  let price = parseFloat(stockObject.p).toFixed(2);
  stockPriceInput.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
  stockPriceInput.value = price;  
  lastPrice = price;
};
<input type="text" id="btc-price" value="" />

  • Related