2

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;
5
  • If you want to access the value outside the class, consider move the value to the parent state and let the parent pass the value to which component who needs it Commented Jul 29, 2018 at 2:12
  • @EdwinHarly I am very new to ReactJS (started a few days ago) so can you offer a bit more explanation. Also, if you can add an example that would be even better. Commented Jul 29, 2018 at 2:24
  • Post a new question about it as it is OOT Commented Jul 29, 2018 at 2:32
  • On a second thought, about state management and stuff, I think it's a fairly common question, so I guess it isn't very hard to search for Commented Jul 29, 2018 at 2:35
  • What is an OOT? Commented Jul 29, 2018 at 2:37

3 Answers 3

1

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)}>
Sign up to request clarification or add additional context in comments.

6 Comments

After I made your change I received the following error: TypeError: Cannot read property 'target' of undefined 19 | 20 | handleChange(event) { > 21 | this.state.inputValue = event.target.valueAsNumber; 22 | console.log('Form value: ' + this.state.inputValue); 23 | event.preventDefault(); 24 | }
Used this to fixed error above, stackoverflow.com/questions/46389220/… But after I reloaded the form and filled out the input field the value was automatically sent with after hitting 'p' for PM. I have been on this all day troubleshooting and eveything I have found said onSubmit={this.handleSubmit} and event.preventDefault(); in the handleSubmit(event) function should work but it is not.
Still acting the same. Also received the following warning: Warning: Expected onSubmit listener to be a function, instead got a value of string type.
Sorry about that, answering from phone, see corrections. The {..} need to be used in place of the ".."
Made the following change and same behavior: <form onSubmit={(event) => this.handleSubmit(event)}>
|
1

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

6 Comments

@N6DYN Here is the working example
Made the changes to both handleSubmit and handleChange and the application is still acting the same.
@N6DYN Is it showing the error or do not getting the expected functionality
I tried your example and it is acting the same as mine. The value is being submitted as soon as the input box is filled. I would like to submit the value only after pressing the submit button.
@N6DYN I have made some more edits.Please do check and update
|
0

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]

6 Comments

this worked. And thanks for the explanation; greatly appreciated.
I would also like to be able to input the seconds. Currently I can only input HH:mm. Do I need to ask another question for that?
I made the following changes to handleSubmit() handleSubmit(event) { // this.setState({ // inputValue: event.target.valueAsNumber // }); this.state.inputValue = event.target.valueAsNumber; console.log("Input Value:", event.target.valueAsNumber) event.preventDefault(); } and received the following error: Input Value: undefined
@N6DYN I guess you are trying to add those bugs again into the code by using this.state.inputValue, it's not prescribed and not allowed. Thanks for asking, glad to help you over skype too:- connect.ronit
I am trying to have the input converted to Unix time (Epoch).
|

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.