3

How to invoke react handler using jquery val() method?

Below is a simple react component with input field. Whenever the value changes the onChange event handler is fired and value is set to state of the component.

  var Hello = React.createClass({

   getInitialState: function(){
     return {
        val: this.props.defVal || ""
     };
   },
   onChange: function(event){

    var newVal = event.target.value;
    console.log("changed", newVal);
    this.setState({val: newVal});

   },
   render: function() {
     return <div>
     <input id = "asd" className = "asd" value = {this.state.val} onChange = {this.onChange}/>
     Hello {this.props.name}</div>;
   }

  });

  React.render(<Hello name="World" />, document.getElementById('container'));

However the onChange handler is not fired when i use jquery val method. Like $('#asd').val("asd");

Is there a way i can invoke the handler using jquery val function?

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
Softwareddy
  • 791
  • 1
  • 7
  • 9
  • 3
    `.val()` never triggers a change event (react or otherwise). Also you should find a way to communicate with the component without using jQuery or dom. – Brigand Jun 29 '15 at 13:49
  • 1
    Easier said than done when you're trying to get React and a jQuery plugin to work nicely together. – sent1nel Aug 17 '15 at 16:40
  • And almost three years later, this question remains unanswered :(. https://stackoverflow.com/questions/49783314/trigger-change-event-for-react-rendered-input-type-range – Radu Luncasu Apr 12 '18 at 08:58

1 Answers1

0

You need to:

1.Set a ref on the input item, like:

<input id="asd" className="asd" value={this.state.val}
ref={(myInput) => { this.myInput = myInput; }/>

...now you can refer to this.myInput.value .

Than you can

2.run arbitrary code using some other event, such as onBlur:

<input id="asd" className="asd" value={this.state.val}
ref={(myInput) => { this.myInput = myInput; }
onBlur={this.onBlur.bind(this)} />

(or newer ES6 syntax for the same)

...and:

3.make a function to handle it, which uses your ref:

onBlur(e) {
    var newVal = this.myInput.value; // uses the ref
    console.log("changed", newVal);
    this.setState({val: newVal});
}

NB:

Contrary to what I've read on pages that aren't react-specific, you can't do:

$('#asd').val("asd").change();

... (There's at least one such SO answer that got me naively excited!)

Community
  • 1
  • 1
Ben Wheeler
  • 6,788
  • 2
  • 45
  • 55