简体   繁体   中英

Printing HTML Input Value to Console on Click

I wrote a code like this:

@page
@model AddClassPage
@{
    ViewData["Title"] = "Add Class";
}

<div class="p-3 mb-2 bg-dark text-white">
    <h2 class="display-4">Add Class</h2>
</div>
<form>
  <div class="form-group">
    <label for="teacherIdInput">Class ID (number only):</label>
    <input type="number" class="form-control" min="0" id="classID" placeholder="Class ID">
  </div>
  <div class="form-group">
    <label for="teacherNameInput">Class Name:</label>
    <input type="text" class="form-control" id="classNameID" placeholder="Class Name">
  </div>
  <button type="submit" class="btn btn-grey">Add</button>
</form>

<script>
   form.addEventListener('submit', function(){
      console.log(input.value);
   });
</script>

My goal is to print the Input value to the console when I click the btn btn-grey class button. But I just couldn't. Could you help? I'll save it to Microsoft SQL after testing if the data comes in.

You would have to use event object to access input elements on target property. The id that you specified on inputs will indicate which input to access on target object.

Additionally you can also preventDefault behaviour of form submission using e.preventDefault()

form.addEventListener("submit", function(e) {
  e.preventDefault();
  console.log(e.target.classID.value);
  console.log(e.target.classNameID.value);
});

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