How to alert the text someone writes in for example recipient/ message Code Answer

I just started playing with DOM, and I am trying to do the following thing: 1.I created a form that has a recipient/ message and two buttons : submit/ reset;

<form id="event">
<!-- Recipient -->
Recipient <input type="text" required class="msg" > <br>

<!-- Message -->
<label for="message" >Message</label>

<textarea rows="4" cols="30" class="msg" > </textarea>
<br>
<input type="submit" value="Submit">
<input type="reset">
2. When I press submit, I want to send an alert with what I wrote in those two fields. The problem is that here I get stuck, I managed only to alert either the recipient or the message. Here’s my code:
document.querySelector('#event').addEventListener('submit', function(a) {

a.preventDefault() alert(a.target.elements.input.value)

}) Did I make this matter way too complex? I feel completely stuck at the moment, a tip would be amazing. Thanks in advance, wish you a good day!

Answer

Not necessarily the best way to do it, but it’s working.

document.querySelector("#form").addEventListener("submit", event => {
  event.preventDefault();
  const recipient = document.querySelector('[name="recipient"]').value;
  const message = document.querySelector('[name="message"]').value;
  window.alert(`${recipient}: ${message}`);
});
<form id="form">
  <label for="recipient">Recipient</label>
  <input type="text" required class="msg" name="recipient">
  <br>
  <label for="message">Message</label>
  <textarea rows="4" cols="30" class="msg" name="message"></textarea>
  <br>
  <input type="submit">
  <input type="reset">
</form>

You may also learn how to select name attributes using this. It’s always useful to know.

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji