1

Создаю чат. Необходимо вывести текст из инпута. Написал код, но он почему-то не выводит текст из инпута. Помогите пожалуйста решить данную проблему

function input() {
  var input_taker = document.getElementById('input').value;
  document.getElementById('msg').innerHTML = input_taker;
}
.chat {
  width: 800px;
  height: 400px;
  border: 2px solid red;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
<div class="chat">
   <div class="msg" id="msg">
    
   </div>
  <div class="send-line">
    <div class="get-name">
      <p>введите ваше имя</p>
      <input type="text"  id="input">
    </div>
    <div class="get-msg">
      <p>введите ваш текст</p>
      <input type="text" id="input">
      <button>Отправить</button>
    </div>
  </div>
</div>

1
  • 1
    два инпута с одинаковым идентификатором - это подсказка 1 авг 2021 в 13:59

1 ответ 1

1

У вас два элемента с id="input", поэтому программа не знает откуда брать текст. И вы не навесили обработчик событий на кнопку. Правда я не обработчика навесила, а просто использовала аттрибут onclick

function input() {
  var username = document.getElementById('username').value;
  var input_msg = document.getElementById('input_msg').value;
  document.getElementById('msg').innerHTML = `${username}: ${input_msg}`;
}

   
.chat {
  width: 800px;
  height: 400px;
  border: 2px solid red;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
<div class="chat">
   <div class="msg" id="msg">
    
   </div>
  <div class="send-line">
    <div class="get-name">
      <p>введите ваше имя</p>
      <input type="text"  id="username">
    </div>
    <div class="get-msg">
      <p>введите ваш текст</p>
      <input type="text" id="input_msg">
      <button onclick="input()">Отправить</button>
    </div>
  </div>
</div>

2
  • 1
    спасибо большое за столь развёрнутый ответ, очень помогли!
    – kiskiskit
    1 авг 2021 в 20:45
  • 1
    Рада, что смогла помочь, удачи)
    – Vetedde
    1 авг 2021 в 21:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.