skip to Main Content

I am trying to collect responses from an HTML field in a way that will create a new object with a series of key/value pairs for each of the form fields. Right now every field is returning a string value. I need help with:

  • making the ‘pages’ field return a number value rather than a string
  • making the checkbox return a boolean value ‘true’ if checked and ‘false’ if left unchecked

For context: I am trying to create a program that allows the user to fill out a simple form with information about a book (title, author, number of pages and whether they’ve read it or not (the checkbox)); each book will be a new object in an array, and this will be used to display the books in a "library" on the page where the user can then in the future check/uncheck the checkbox to indicate whether they have read the book or not.

function handleSubmit(event) {
    event.preventDefault();
    
    const data = new FormData(event.target);

    const obj = Object.fromEntries(data.entries());

    console.log(obj);
}

const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
<body>
    <form>
        <label for="title">Title:</label>
        <input id="title" name="title" type="text">

        <label for="author">Author:</label>
        <input id="author" name="author" type="text">

        <label for="pages">Pages:</label>
        <input id="pages" name="pages" type="text">

        <div class="input-group">
            <label for="checkbox">Check if read:</label>
            <input id="checkboxHidden" value="no" name="checkbox" type="hidden">
            <input id="checkbox" value="yes" name="checkbox" type="checkbox">
        </div>

        <button id="submit">Submit</button>
    </form>
</body>
</html>

I am pretty much a beginner at JavaScript so the simplest solution to accomplish this would be most helpful! Thanks in advance!

2

Answers


  1. There’s a few things to point out here.

    Instead of using Object.fromEntries(data.entries()), you should directly initialise an empty object to store the manipulated data. This is because of your specific requirements. You mention converting the ‘pages’ field to a number and the ‘checkbox’ to a boolean – it is therefore best practice to start with an empty object, which allows you to manually set each key-value pair after making necessary conversions.

    You then should loop through the FormData and manipulate each value as needed. The For...of loop allows you to iterate over each entry in the FormData object so that you can apply specific logic depending on the type of the field (key).

    Using this logic, you can then check if the key is ‘pages’ and then typecast this value to a number. This is done using parseInt(), which allows a string to be parsed as a number.

    Similarly, you can check if the key is ‘checkbox’. The checkbox behaviour in HTML forms usually involves sending a value if the box is checked and not send any value if it is unchecked. You need to add some logic to return true if the box is checked, and false if it is unchecked. The ternary operator checks whether the value is ‘yes’, and then sets it to true – else, it is false.

    Here is a basic implementation with the above in mind and I hope it helps you:

    function handleSubmit(event) {
        event.preventDefault();
        
        const data = new FormData(event.target);
    
        // Create an empty object to store the form values
        let obj = {};
    
        // Loop through FormData entries
        for (let [key, value] of data.entries()) {
            // If the key is 'pages', convert the value to a number
            if (key === 'pages') {
                obj[key] = parseInt(value);
            }
            // If the key is 'checkbox', convert the value to a boolean
            else if (key === 'checkbox') {
                obj[key] = value === 'yes' ? true : false;
            }
            // For all other fields, store the value as is
            else {
                obj[key] = value;
            }
        }
    
        console.log(obj);
    }
    
    const form = document.querySelector('form');
    form.addEventListener('submit', handleSubmit);
    
    Login or Signup to reply.
  2. Notice the various <input> types there are to implement. One is type=number.

    In terms of converting .checked to boolean (true/false), that’s done like below:

    HTML Inputs

    let checkbox = document.querySelector('input[type=checkbox]')
    checkbox.addEventListener("change", function(e){
      console.log(checkbox.checked);
    })
    <input type=checkbox>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search