Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab html form data in JS

It smells like a trivial one but can't figure it out. I have a html form that is generated dynamically by JS and filled with initial data grabbed from server, DB passed as a parameter to displayResForm. The form is displayed correctly with filled data. Now I want to be able to modify this data through this form and POST it back to DB as JSON format but the problem is I am not able to capture the html form data in my JavaScript.

The form base is as follows:

<form method="POST" id="res-form" name="modForm" onSubmit="modSubmit()">
        {% csrf_token %}
</form>

and it gets built with:

function displayResForm(results) {
    var form = document.getElementById("res-form");

    for (var i = 0; i < results.length; i++) {
        var input = document.createElement("input");
        input.setAttribute("type", "number");
        input.setAttribute("value", results[i][1]);
        input.setAttribute("id", toString(i));
        var label = document.createElement("label");
        label.setAttribute("for", toString(i));
        label.appendChild(document.createTextNode(results[i][0]));

        form.appendChild(label);
        form.appendChild(input);
        form.appendChild(document.createElement("br"));
    }

    var mod = document.createElement("input");
    mod.setAttribute("class", "btn btn-info");
    mod.setAttribute("type", "submit");
    mod.setAttribute("value", "Modify");
    mod.setAttribute("onclick", "modSubmit()");
    form.appendChild(mod);
}

As you can see I have two calls of modSubmit (one in form tag, the other in submit button) but neither works. And I want to grab it (to send POST request to server, not implemented yet):

function modSubmit() {
    //var formData = JSON.stringify($("modForm").serializeArray());
    var formData = $('modForm').serializeArray()
    console.log("formData=", formData);
    alert(formData);
    // todo POST back to server
    return false;
}

The issue is I keep on getting empty formData ...

EDIT:

I can easily get the value of elements manually by

var x = document.getElementById("res-form");
var el = x.elements[1].value;
alert(el);

But I hoped for one-liner.

like image 737
micsza Avatar asked Jun 05 '26 13:06

micsza


1 Answers

The issue you've is in the selector used in the following line :

var formData = $('modForm').serializeArray()
__________________^^^^^^^

This line trys to select a tag called modForm instead of an element that has a name equals to modForm.

Instead you could select your form using :

var formData = $('[name="modForm"]').serializeArray();
//Or also using the id attribute
var formData = $('#res-form').serializeArray();

Hope this helps.

like image 137
Zakaria Acharki Avatar answered Jun 07 '26 09:06

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!