N6DYN
N6DYN

Reputation: 325

ReactJS: Stop input from automatically being submitted

After selecting a date from the dropdown calendar and setting the time the value is automatically submitted. However, I want use the submit button to submit the value. From research I thought, 'event.preventDefault();', statement was suppose to prevent such a thing. Also, is the value stored in inputValue? If it is, how do I access that value from outside the calendar class?

So, again to be clear, I want to submit the value using the submit button.

class Calendar extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                inputValue: '',

            }
            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }


        handleChange(event) {
            this.state.inputValue = event.target.valueAsNumber;
            console.log('Form value: ' + this.state.inputValue);
            event.preventDefault();
        }

        handleSubmit(event) {

            this.state.inputValue = event.target.valueAsNumber;
            console.log('Form value: ' + this.state.inputValue);
            event.preventDefault();
        }

        render() {
            return (
                <div className="Calendar">
                    <form onSubmit="return handleSubmit();">
                        <label>Date/Time</label>
                        <input type="datetime-local" value={this.state.inputValue} onChange={this.handleChange()} />
                        <input type="submit" value="Submit" />
                    </form>
                </div>
                 //{this.render(){return (<UserList />)};
            );
        }
    };
    export default Calendar;

Upvotes: 2

Views: 871

Answers (3)

Harikrishnan
Harikrishnan

Reputation: 1097

Finally i found the problem,the form was submitting automatically because you gave the value attribute as the state.inputValue, which is not required. The onChange attribute is also not required.Please try the following code

class Calender extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ""
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    this.setState({ inputValue: document.getElementById("time").value });
  }
  render() {
    console.log(this.state.inputValue);
    return (
      <div className="Calendar">
        <form onSubmit={this.handleSubmit}>
          <label>Date/Time</label>
          <input type="datetime-local" id="time" />
          <input type="submit" value="Submit" />
        </form>
      </div>
      //{this.render(){return (<UserList />)};
    );
  }
}

Also please not that you may not get the state value immediately after it is set.The working example is here

Upvotes: 1

Ronit Mukherjee
Ronit Mukherjee

Reputation: 405

I tried creating a test app using the code provided by you and therefore analyze the code, I found many issues in the code.

I have written another version of the code, removing the bugs or mistakes. Find the code at JSFiddle. and I am also pasting the basic code(Component Class) here too.

class Calendar extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      inputValue: '',
    }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }


  handleChange(event) {
    this.setState({
        "inputValue":event.target.value
    });
  }

    handleSubmit(event) {
    console.log("Input Value:",this.state.inputValue)
  }

  render() {
    return (
      <div className="Calendar">
        <form onSubmit={this.handleSubmit}>
          <label>Date/Time</label>
          <input type="datetime-local" 
                 value={this.state.inputValue}   
                 onChange={this.handleChange} />
          <input type="submit" value="Submit" />
        </form>
      </div>
      //{this.render(){return (<UserList />)};
    );
  }
};
  1. The issues which were there in the code are the following:- this.state.inputValue = event.target.valueAsNumber setting the state directly is not allowed, therefore I converted the code with this.setState
  2. input type datetime-local expects the value format to be like "1990-11-02T12:59" so replaced it with event.target.value
  3. onChange="return handleChange()" is not the prescribed way to call function of the component class inside render, using () with function name directly call the function on the page load which we don't want, therefore replaced the code with onChange={this.handleChange}
  4. onSubmit="return handleSubmit();" will call the handleSubmit function as soon as the component loads and this is not the prescribed way too, therefore replaced the code with onSubmit={this.handleSubmit}
  5. in handleSubmit function we don't need to set the state again as it's already updated whenever the value of the input changes using the handleChange function. So here if you want then you can call any function of the parent using the this.props.parentFunc(this.state.inputValue) and use the input value further.

For any further query feel free to comment or email me at [email protected]

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30360

The reason for this is that the following line causes handleSubmit() to execute immediately, when the component is rendered:

<form onSubmit="return handleSubmit();">

In order words, when your component renders, it is calling handleSubmit() when "binding a handler" to the forms onSubmit event.

If you revise your code as follows, this will prevent the form from being submit/executed automatically while achieving the desired form submit behaviour:

<form onSubmit={(event) => this.handleSubmit(event)}>

Upvotes: 1

Related Questions