Gregoirelpv
Gregoirelpv

Reputation: 112

Use value of an Input in a function

I'm a bit ashamed to write this topic because even if I got a HTML formation (4 years ago) I can't resolve my problem :

I can't use the value of an input type text in a function, this is my code:

import React from 'react'
//import db from '../../constants/FirebaseConfig'

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        e.preventDefault()
        var name = document.getElementsByName('name')
        console.log(name)
        
    }

    render(){
        return(
            <div className="container">
                <br></br>
                <h3 className="title">Account</h3>
                <form id="form">
                    <br></br>
                    <label>Titre</label>
                    <input type="text" name="name" placeholder="Ici le nom de l'Article"/>
                    <br></br><br></br>
                    <label>Contenue</label>
                    <input type="text" name="content" placeholder="Ici le contenue de l'article"/>
                    <br></br><br></br>
                    <input type="button" value="suivant" onClick={(e) =>this._formSubmit(e)}/>
                    <br></br>
                </form>
            </div>
        )
    }
}

export default Account

After attempting to debug a few times I think the problem is with the var name object which is a NodeList<input> type. My goal is to stock the 'name' and 'content' value in a firebase db.

Thank You

Upvotes: 2

Views: 256

Answers (3)

Mosia Thabo
Mosia Thabo

Reputation: 4267

Without suggesting any workaround but trying to make exactly what you posted work the way you're expecting it to, Here's what I figured out you were trying to do:

Your Problem:

_formSubmit(e) {
    e.preventDefault()
    var name = document.getElementsByName('name') //Get's a list of Elements with the given name
    console.log(name) // This prints the list contained in name variable

}

The Solution:

_formSubmit(e) {
    e.preventDefault()

   // Assuming you're trying to print the values of all inputs
   // First - Get all elements whose values you want to log, as per your initial code
    var name = document.getElementsByName('name'); // returns ListNode<HTMLElement> 

   // Now loop through each input and print it's value to console
   name.forEach(
     function(input){
      console.log(input.value); //Print the value of each input listed
     }
   );    
}

Upvotes: 1

learner62
learner62

Reputation: 610

On HandleChange function, it will automatically check the name where you have changed, and it will update the value

import React, { Component } from "react";

export default class App extends Component {
  state = {
    name: "",
    content: "",
    datas: []
  };
  handleChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const data = {
      name: this.state.name,
      content: this.state.name
    };
    this.setState({
      datas: [...this.state.datas, data],
      name: "",
      content: ""
    });
  };
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="name"
            value={this.state.name}
            onChange={this.handleChange}
            placeholder="Ici le nom de l'Article"
          />
          <input
            type="text"
            name="content"
            value={this.state.content}
            onChange={this.handleChange}
            placeholder="Ici le nom de l'Article"
          />
          <button>Submit</button>
        </form>
        <div>
          {this.state.datas.map(item => {
            return (
              <div key={Math.random()}>
                <h6>{Math.random()}</h6>
                <h4>Name:{item.name}</h4>
                <h4>Content:{item.content}</h4>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

Upvotes: 1

tmdesigned
tmdesigned

Reputation: 2254

Two things:

getElementsByName is plural -- note the 's' in 'Elements'. So it doesn't just return one element, it returns a list, even if there's just one.

Since you are using React, you don't need to pull the value of the input that way at all. Instead, on the input itself, just add a value and onChange property, and then track the value being typed in there as state.

You already have a spot for them in your state, so just go ahead and use that. You'll track it live as they type, not just at form submission.

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        //just process your form _submission_ here           
    }

    onChangeName = (e) => {
        this.setState({
           name: e.target.value
        });
    }

    render(){
        return(
            <div className="container">
                <br></br>
                <h3 className="title">Account</h3>
                <form id="form">
                    <br></br>
                    <label>Titre</label>
                    <input type="text" name="name" placeholder="Ici le nom de l'Article" value={this.state.name} onChange={this.onChangeName} />

Upvotes: 6

Related Questions