Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access form data nested inside divs (TypeScript)

In a following code I want to access user data written in a form each time user presses an enter key after typing some text data inside an input field in chat-form. Do you have any idea how can I access the following text-data using TypeScript? I have already tried with jQuery but none of the tested code seems to work. I am new to web-dev but very eager to learn new things.

<div id="chat-container">

  <div id="search-container">
    <input type="text" placeholder="search" />
  </div>
  <div id="conversation-list">

  </div>
  <div id="new-message-container">
    <a href="#" id="test">+</a>
  </div>
  <div id="chat-title">

  </div>
  <div id="chat-message-title">

  </div>
  <div id="chat-form">
    <input id="chat-form" type="text" placeholder="Type a message!" />
  </div>
  
</div>
like image 911
S.Rucinski Avatar asked Sep 11 '26 15:09

S.Rucinski


2 Answers

first, you should use a semantic HTML by using form tag instead of div so u can use enter key to handle the submit action. second, it is not an appropriate way to duplicate an id for two different elements because id is a unique identifier for the element. finally here is a simple form and it might be helpful. HTML:

<form id="my-form">
  <input type="text" id="my-input" />
  <button type="submit" id="submit-btn">send</button>
</form>

JS:

const formEl = document.getElementById("my-form") as HTMLFormElement;
const inputEl = formEl.querySelector("my-input") as HTMLInputElement;
const submitBtnEl = formEl.querySelector("submit-btn") as HTMLButtonElement;
formEl.addEventListener("submit", e => {
    e.preventDefault();
    // do what you want
});
inputEl.addEventListener("change", (e:Event|any) => {
    console.log(e.target.value)
    // do what you want
})
like image 82
Abdelmonaem Shahat Avatar answered Sep 14 '26 06:09

Abdelmonaem Shahat


Before the answer: you have duplicated id="chat-form"

<div id="chat-form">
  <input id="chat-form"type="text" placeholder="Type a message!"/>
</div>

Example

// select element
const elInput: HTMLInputElement = document.querySelector(`#chat-form-input`)

// add onkeypress listener
document.onkeypress = function (e: any) {

    // use e.keyCode
    if (e.key === 'Enter') {
      // code for enter
      console.log(elInput)
      console.log(elInput.value)
    }
}
<body>
  <div id="chat-container">
    <div id="search-container">
        <input type="text" placeholder="search"/>
    </div>
    <div id="conversation-list">

    </div>
    <div id="new-message-container">
      <a href="#" id="test">+</a>
    </div>
    <div id="chat-title">

    </div>
    <div id="chat-message-title">

    </div>
    <div id="chat-form-container">
      <input id="chat-form-input" type="text" placeholder="Type a message!"/>
    </div>
  </div>
</body>
like image 44
qiAlex Avatar answered Sep 14 '26 05:09

qiAlex