Ravshan Gafurov
Ravshan Gafurov

Reputation: 21

how to pass a parameter in onKeyDown action?

document.addEventListener('keydown', handle);
  function handle(e) {
   let value = document.getElementById("t11").value 
    if(e.code == "Space"){
      if(value =="n")value="t"
      else if(value == "t")value="P"
      else if(value == "P")value="S"
      else if(value =="S")value="n"
      else value ="n"
      document.getElementById("t11").value = value
    }
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.3.2/react-dom.min.js"></script>
<html>
<body>
<label>Focus the input first (e.g. by clicking in it), then try pressing Space.</label>
<input type="text" id="t11"   className="attendanceInput"  readonly/>
</body>
</html>

I have an input which, by pressing the spacebar, changes the values :

<input type="text" id="11"  onKeyDown={this.handleKeyDown.bind()} className="attendanceInput" readOnly/>
 handleKeyDown(e) {
    if(e.keyCode == 32){
      let value = e.value
      if(value =="n")e.value ="t"
      else if(value == "t")e.value="P"
      else if(value == "P")e.value="S"
      else if(value =="S")e.value="n"
      else e.value ="n"
      document.getElementById("11").value=e.value
    }
  }

and I need to take the input id to update the value and other actions. How can I do this? Thanks.

Upvotes: 0

Views: 1918

Answers (1)

wentjun
wentjun

Reputation: 42556

One way of approaching this issue would be to call e.currentTarget.id within the handleKeyDown method, which will return the id of the input element.

However, if you wish to update the value of the input element, you will need to maintain a local state within your component, and subsequently update the state by binding the state update the onChange event.

<input value={input1}  onChange={(e) => this.handleInput(e)} className="attendanceInput" />

Upvotes: 1

Related Questions