WebMasterCampus
WEB DEVELOPER Resources

jQuery Convert Form Data to Javascript Object

jQuery Convert Form Data to Javascript Object


jQuery Convert Form Data to Javascript Object

The serializeArray method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types.

Code Example

    <form>
        <div><input type="text" name="firstName" value="James" id="firstName"></div>
        <div><input type="text" name="lastName" value="Barr" id="lastName"></div>
        <div><input type="hidden" name="temp_id" value="30" id="temp_id"></div>
        <div>
          <textarea name="comments" rows="8" cols="40">Good service</textarea>
        </div>
        <div><select name="rating">
          <option value="1" selected="selected">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select></div>   <br>     
        <div>
          <input type="submit" name="submit" value="Submit" id="submit">
        </div>
    </form>

    <script src="https://code.jquery.com/jquery-git.js"></script>
    <script>
        $("form").submit(function(event){
            let form_obj = $(this).serializeArray();
            form_obj.forEach(function(inputObj){
                console.log(inputObj.name + ":" + inputObj.value);
            })
            event.preventDefault();
        });
    </script>
Created with love and passion.