HTML Question

jQuery on click not returning any value

What I am trying to do is to get all inputs and data when someone click the submit button.

My code HTML is this:

<form id="form" action="index.php" method="POST" class="register" name="Register">
<label>Patient Name:</label>
<input id="pname" name="pname" placeholder="John Doe" type="text" data-role="justText" value=""><br><br>
<label>Phone Number:</label>
<input id="ptel" type="tel" name="ptel" value=""><br><br>
<label>Email:</label>
<input id="pemail" placeholder="example@gmail.com" type="email" value=""><br><br>
<button id="submit" class="submit" type="submit" name="register">Registrar</button>
</form>


Don't know if it's the best use the button or input tag for submit the form. And the jQuery to handle what I am trying to do is this:

jQuery.fn.extend({
hello: function () {

submitbutton = $(this).find('button').attr('id');
$inputs = $(this).find('input');

knowInputs = function() {
$inputs.each(function () {
console.log( $(this).attr('name') );
});
}

$('#'+submitbutton).on('click', function () {
knowInputs();

})
return this;
}
});


So, I put the form ID and init the function like this:

$(#form).hello();


P.D.: If I put the code knowInputs outside the on(click), it seems to work fine. My problem is when I am trying to gather all when clicking the submit button.

Any help shall be appreciated. Thanks in advance!

Answer Source

Forms have a native Javascript event, submit. jQuery also has a function, $.serialize which will turn a form into an encoded URL string, which is probably the most standard format you'd want it in. You can easily convert this into JSON or a JS Object.

$('#form').submit(function(e){
    e.preventDefault();
    return $(this).serialize();
});