Clearing form after submit using jquery [duplicate]

I have a working newsletter form (name, email) using Node.js and jquery the only problem is the form does not clear once the email is submitted using the "sign-up" button.

I have tried using an empty string ' ' after onclick as well as the .reset() form method. Both of these approaches work, however it's clearing the email address and preventing it to be sent to Mailchimp. I've tested it with a handful amount of email addresses and nothing goes through. As well, my terminal messages show 'email_address: ' as an empty string. I'm assuming I'm ordering my code incorrectly? Any direction/feedback is appreciated. Also, please let me know if I need to add my Node.js code.

HTML:

<form action="/" method="post" id="myForm">
    <h2 class="text-center mt-5"> Sign-Up Newsletter</h2>
    <p>Using Mailchimp API</p>
    <div class="form-group">
        <input type="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Name" style="width: 400px;">
    </div>
    <div class="form-group">
        <input type="email" class="form-control" id="email" placeholder="Email" style="width: 400px;">
    </div>
    <p id="demo"></p>
    <button type="submit" class="btn btn-info" id="submit" onclick="myFunction()" style="color:#fff; margin-bottom: 70px; width: 190px;">Sign up</button>
</form>

JS

var $ = require('jquery');


$('form').submit(function(event) {
    var userEmail = $('#email').val();
    console.log(userEmail);

    event.preventDefault();
    $.ajax({
        url: '/',
        type: 'POST',
        data: {
            email: userEmail
        },
        success: function(response) {
            console.log(response);

        },

    });
});

//Message after newsletter sign-up

function myFunction() {
    document.getElementById("demo").innerHTML = "Thank You, for signing up! You are now on our mailing list!";

}

Node.js

const express = require('express');
const app = express();
const bodyParser = require("body-parser");

//middleware
app.use(express.static(__dirname + "/public"));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

//connecting cloud i9 host
app.listen(process.env.PORT, process.env.IP, function() {
    console.log("The Server Has Started!");
});

//route
app.post('/', function(req, res) {
    addEmailToMailchimp(req.body.email);
    res.end('SUCCESS!');
});

function addEmailToMailchimp(email) {
    var request = require("request");

    var options = {
        method: 'POST',
        url: 'XXXXXXXX',
        headers: {
            'postman-token': 'XXXXXX',
            'cache-control': 'no-cache',
            'content-type': 'application/json',
            authorization: 'Basic XXXXX},
        body: { email_address: email, status: 'subscribed' },
        json: true
    };

    request(options, function(error, response, body) {
        if (error) throw new Error(error);

        console.log(body);
    });
}

Answers:

Answer

You could do the following to achieve this:

$(function() {

  $('form').submit(function(event) {
    var userEmail = $('#email').val();
    console.log(userEmail);

    event.preventDefault();
    $.ajax({
        url: '/',
        type: 'POST',
        context : this, // <-- add this
        data: {
            email: userEmail
        },
        success: function(response) {
            console.log(response);

            $(this)[0].reset() // <-- resets the form
        },

    });

  });

});
Answer

If you want to clear form on the success of AJAX call then used $('#myForm')[0].reset(); this inside ajax call or if you want clear form on the submission of the form then used $(this)[0].reset() outside of the ajax call.

$.ajax({
    url: '/',
    type: 'POST',
    context : this, // <-- add this
    data: {
        email: userEmail
    },
    success: function(response) {
        console.log(response);

        $('#myForm')[0].reset(); // used this
    },

});
Answer

You can do like this. Straight forward way to clear only input textboxes (you can alter this code to clear all inputs as per ur need, for Radio, Checkboxes etc.,) within a form using jQuery.

$('#myForm').find("input[type=text]").val("");

Answer

There are 3 ways to resetting or clearing form using jquery:

reset() and trigger reset method will clear only textfield and textarea etc,

it will not clear checkbox,select or radio button values for clearing all elements in form i prefer 3rd method for all elements.

But first 2 methods are easy and simple, and if you are not using all type of elements of form, but using only textfields and textareas as here in question then reset() and trigger('reset') will do it exactly the same.

  1. Using trigger reset

    $('#form_id').trigger("reset");
    
  2. Using reset()

    $('#form_id')[0].reset();
    
  3. Others For all elements

    $("#form_id").find('input:text, input:password, input:file, select, textarea').val('');
    $("#form_id").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.