jrich523 jrich523 - 2 years ago 88
Javascript Question

Javascript to update input is overwritten by placeholder

I have a simple input box with a placeholder value. There is a simple function that updates its value

socket.on('barcode', function (data) {
console.log('data received')
var barcodeObj = document.getElementById("barcode")
barcodeObj.value = data;

I set a BP on this and the code actually inserts the barcode correctly just fine, however after checking that the function sets it correctly i continue running the app and then its quickly overwritten by the placeholder again.

This is running ReactJS and there is an onChange event, but, I would expect that to fire off correctly just fine.

the input is defined like this


And the handler is setup like so

handleBarcodeChange: function(e) {
this.setState({barcode: e.target.value});

which, isnt doing anything crazy.

what am i missing here?


I was able to get it working by injecting the following code in to my DeviceForm react class.

componentDidMount: function () {
var that = this;
this.socket = io();
this.socket.on('barcode', function (data) {
console.log('data received')
that.setState({barcode: data});

This is from this code http://code.runnable.com/VOIYIALkqgAnHDmj/node-js-socket-io-and-react-js

Answer Source

I think you might just want to do something like this:

socket.on('barcode', function (data) {
    console.log('data received')
    this.setState({barcode: data});

setState should automatically update the DOM for you, meaning that this.state.barcode in your input will be automatically updated. Calling barcodeObj.value = data; will simultaneously trigger onChange, which might be causing your issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download