Vasalath
Vasalath

Reputation: 103

How to grab form input data using jQuery?

I have a html form and once a user enters data and click submit I want to grab the entered values using jQuery.

<form class="bmlf-form needs-validation" method="POST">
  <input type="text" id="firstName" name="First Name">
  <input type="text" id="lastName" name="Last Name">
  <button type="submit" id="btnSubmit" formmethod="POST">SUBMIT</button>
</form>

Here is the jQuery function I wrote

$(function(){
  $("#btnSubmit").click(function(e){
    var data = {
      FirstName: $("#firstName").val().trim(),
      LastName: $("#lastName").val().trim(),
    };
  });
});

Previous developer wrote this piece of code. I am wondering if it has something to do with my code ? as its using the same form id ".bmlf-form" or I can just ignore it.

// This onload event is required for the bootstrap event to work

window.addEventListener("load", () => {
  $(".bmlf-form").on("submit", event => {
    event.preventDefault(event);
    const values = $(event.target).serializeArray();
    console.log(values);
  });
});

Upvotes: 1

Views: 507

Answers (1)

brk
brk

Reputation: 50291

Pass the selector type.Since this is id selector you need to put #.Also if you are using ajax use e.preventDefault()

$("#btnSubmit").click(function(e){

Upvotes: 1

Related Questions