Search code examples
javascriptjsonhtmlform-data

Pass html5 form custom attributes to JSON


This is the HTML that i created for the registration page

<form role="form" action="" method="post" id="register_form">
        <input type="text" id="facebook-autocomplete" name="facebook" class="form-control mdb-autocomplete GJ-search">
        <input type="text" id="beatport-autocomplete" name="beatport" class="form-control mdb-autocomplete GJ-search" required>
        <input type="email" id="inputValidationEmail" name="email" class="form-control" >
        <input type="password" id="inputValidationPass" name="password" class="form-control" >
        <input type="checkbox" class="custom-control-input" name="termsAndConditions" id="termsAndConditions" >
        <input type="checkbox" class="custom-control-input" name="gdprAccept" id="gdpr" >
        <button class="btn btn-outline-info btn-rounded btn-block my-4 waves-effect z-depth-0" value="Submit" type="submit">Sign up</button>
</form>

This is the JavaScript that extracts the form to JSON and console logging it and it works.

//stringify form to JSON string
const serialize_form = form => JSON.stringify(
    Array.from(new FormData(form).entries())
         .reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
    );

$('#register_form').on('submit', function(event) {
    event.preventDefault();
    const json = serialize_form(this);
    console.log(json);
});

I add two new attributes to the beatport input by adding this jquery

$('.beatport #beatport-autocomplete').attr('data-beatport-id', "id pulled from api");
$('.beatport #beatport-autocomplete').attr('data-beatport-name', "name pulled from api");

The Json Result is after adding two new attributes is:

{"facebook":"big show","email":"[email protected]","password":"fsdghfjgh","termsAndConditions":"on","gdprAccept":"on"}

You see that the two new attr are missing and when I add them the input looks like this:

<input type="text" id="beatport-autocomplete" name="beatport" class="form-control mdb-autocomplete GJ-search" required data-beatport-id="12345" data-beatport-name="artist name">

and the JSON result should be like this:

{"facebook":"big show","beatportId":"12345","beatportName":"artist name","email":"[email protected]","password":"fsdghfjgh","termsAndConditions":"on","gdprAccept":"on"}

Solution

  • If you want to add data to your form you can use hidden input and set the value via js

    HTML <input type="hidden" name="beatportID">

    JS $('[name="beatportID"]').attr('value', 'my data');