简体   繁体   中英

Form help(HTML/JS)

I'm (very) new to web development and am working on learning back-end currently.

I am trying to figure out how to use multiple inputs inside a form, but am struggling to get the actual input, instead of the element itself using this code to create the form:

<form id="newPostForm">
  <input name="titleInput" placeholder="title"><br>
  <input name="bodyInput" placeholder="body">
  <button>Submit</button>
</form>

and this JS to try and output the user input to the console:

const newPost = document.getElementById("newPostForm")
const title = document.querySelector(".titleInput")
const body = document.querySelector(".bodyInput")

newPost.addEventListener("submit", (e) => {
    e.preventDefault()
    console.log(title, Body)
})

When I hit the submit button the console displays null null . This is probably a super simple question, but I'd appreciate any help.

After fixing the case issue with your body variable, you need to get the value of the inputs by accessing their value property. Then you want to move those variables into your submit handler, otherwise you're only getting the value once, when the page loads, and they're blank:

 const newPost = document.getElementById("newPostForm"); newPost.addEventListener("submit", (e) => { const title = document.querySelector(".titleInput").value; const body = document.querySelector(".bodyInput").value; e.preventDefault() console.log(title, body) })
 <form id="newPostForm"> <input name="titleInput" class="titleInput" placeholder="title"><br> <input name="bodyInput" class="bodyInput" placeholder="body"> <button>Submit</button> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM