0

i want to get a value of an input but it appears theres something wrong that i cant figure it out.

import React, { Component } from 'react';
...   
      this.state = {
      json:JSON.parse(props.data),
      objet: '',
      id: '',
      click: function(click){
        var a = document.getElementById("click").value;
        alert(a);
        a = null;
      }
    };
 ...
     {this.state.json[1].map(i => (
       ...
        <input onClick={this.state.click} value={i.id} id="click" ></input>
       ...
      ))}

in the browser i see this : Screenshot from my browser

the problem is when i click on one of the two inputs it alwaaays shows 2.

i can't see why it's not working Please help me out i'm stuck.

2
  • 1
    Can you share a minimal working code? I can't tell clearly where is the problem. I suspect from that onClick function that you have in the component state. Commented May 21, 2020 at 4:23
  • 1
    thank you soo much brother for your time , hopefully i solved it Commented May 21, 2020 at 4:38

1 Answer 1

1

You have at least two different html elements with the same id ("click"). Because of that document.getElementById("click") may return element which you are not expecting. In order to fix this try to change id="click" on id={"click-" + i} and update the corresponding onClick function.

Sign up to request clarification or add additional context in comments.

3 Comments

yeah you are absolutely right i didnt see that the id is duplicated. thanks man i solved it in a weird way : i changed the function to this : ` click: function(id){ alert(id);}` and the inputs to this : <input onClick={() => this.state.click(i.id)} value={i.id} id="click"></input> hopping that it will not throw any problems in the future
Mb You should try to use function that returns another function, because I am not sure how the code You listed suppose to work. Try this: click : id => () => alert(id)
you are right , my syntax thors an error and the solution is as you said click: (id) =>{}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.