allegory allegory - 9 months ago 27
jQuery Question

JQuery cannot get values

I can get a text/val from a text area. But I am trying to get an input from a Form. I've read a bunch of articles to try different things but I can only get a value/text from my textarea.

Tried serialize, get the same result. I have a msg that prints out and my NodeJS server spits out same result on console. I've tried using classes instead of IDs. Tried adding type="text" to customer didn't work. Tried with JSON.stringify and without for both cust and date. Do input fields not work? I'm using JQuery 3.1.1

Response says: {date: '', customer: '""', notes: 'notes go here'}

<form name="loginForm" method="post" action="/sendReturnForm" id="returnForm">

<p>Date:</p>
<input type="date" name="formDate" id="formDate"/>
<p>Customer:</p>
<input name="formCustomer" id="formCustomer"/>
<p>Notes:</p>
<textarea rows="5" cols="40" id="notes">Notes go here</textarea>
</form>

<script language="JavaScript">
$(document).ready(function () {
var values = {
date: $("#formDate").text(),
customer: JSON.stringify($("#formCustomer").text()),
notes: $("#notes").text()
};

$(".submitButton").click(function () {
$.ajax({
url: '/sendReturnForm',
type: 'POST',
data: JSON.stringify(values),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (msg) {
alert(JSON.stringify(values));
}
});
});
});
</script>

Answer Source

You need to collect data when you click submit button:

$(".submitButton").click(function (event) {
    event.preventDefault();
    var values = {
        date: $("#formDate").val(),
        customer: JSON.stringify($("#formCustomer").val()),
        notes: $("#notes").text()
    };
    $.ajax({
        url: '/sendReturnForm',
        type: 'POST',
        data: JSON.stringify(values),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        success: function (msg) {
            alert(JSON.stringify(values));
        }
    });
});