Emir Bolat
Emir Bolat

Reputation: 1049

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.

Upvotes: 0

Views: 782

Answers (1)

Pratik Wadekar
Pratik Wadekar

Reputation: 1274

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);
});

Upvotes: 1

Related Questions