Home > Enterprise >  Printing HTML Input Value to Console on Click
Printing HTML Input Value to Console on Click

Time:07-29

I wrote a code like this:

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

<div >
    <h2 >Add Class</h2>
</div>
<form>
  <div >
    <label for="teacherIdInput">Class ID (number only):</label>
    <input type="number"  min="0" id="classID" placeholder="Class ID">
  </div>
  <div >
    <label for="teacherNameInput">Class Name:</label>
    <input type="text"  id="classNameID" placeholder="Class Name">
  </div>
  <button type="submit" >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.

CodePudding user response:

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