Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
How to submit form on Enter using DIV

I'm trying to figure out how to make my form submit when enter is pressed inside the div that is acting as input. Any help?

Here is my code.

const socket = new WebSocket("ws://localhost:5000");

const Chat = () => {
  
  let divText = "";
  
  const SendMessage = (event) => {
    event.preventDefault();
    console.log(divText);
    divText = "";
  }

  const HandleChange = (event) => {
    
    divText = event.target.textContent;
  }

  return (
    <div className='chat-div'>
        <div className='chat-box'>
          <span className='razmak'></span>
        </div>
        <form className='input-form' onSubmit={SendMessage} spellCheck='false'>
            <div className='chat-input' contentEditable='true' onInput={HandleChange}></div>
            <button className='send-button' type='submit'><AiOutlineSend/></button>
        </form>
    </div>
  )
}

export default Chat;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

What I'd do is update your div to use an onKeyDown like this:

const socket = new WebSocket("ws://localhost:5000");

const Chat = () => {
  let divText = "";

  const sendMessage = (event) => {
    alert("submit");
    event.preventDefault();
    console.log(divText);
    divText = "";
  };

  const handleChange = (e) => {
    divText = e.target.textContent;
    if (e.key === "Enter") {
      sendMessage(e);
    }
  };

  return (
    <div className="chat-div">
      <div className="chat-box">
        <span className="razmak"></span>
      </div>
      <form className="input-form" onSubmit={sendMessage} spellCheck="false">
        <div
          className="chat-input"
          contentEditable="true"
          onKeyDown={(e) => handleChange(e)}
        ></div>
        <button className="send-button" type="submit">
          jhgj
        </button>
      </form>
    </div>
  );
};

export default Chat;

There's a couple of other things, some which I've not included above:

  • Lowercase the method names if they don't return JSX
  • The divText should ideally use the useState React hook
  • Consider using a standard input rather than a div, as this is semantically more correct, and accessible for people using screen readers.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!