CM forms, jQuery + $(this). Applying to all classes on page

77 Views Asked by At

I am using Campaign forms on a site I am building. There is multiple forms that follow the same structure (see below) and use the same class names.

Am using AJAX to post the form to Campaign Monitor, also to add class if it returns an error message, and show another message if it is correct. This works fine, however it applies the error class to all forms on that page. Which on the homepage can be up to 4, due to the nature of the design.

If the submission is successful, the response shows, if it is not there is the class or error (just a red border) applied to the input. I've done something similar before, but can't work it out today.

The issue is the response or errow will show on all forms on current page until site is refreshed

        <form action="http://thesocialmediacollege.createsend.com/t/t/s/digdk/" method="post" class="cm-form">
            <input class="input-white" id="fieldName" name="cm-name" type="text" placeholder="First Name" required="" />
            <input class="input-white" id="fieldtrdllu" name="cm-f-trdllu" type="text" placeholder="Last Name" required="" />
            <input class="input-white email-input" id="fieldEmail" name="cm-divur-divur" type="email" placeholder="Email" required />
            <button class="input-btn btn-blue" type="submit" id="submit">Submit</button>
            <h3 class="ash form-alert response">Thanks! We will be in touch.</h3>
        </form>
$('.cm-form').submit(function (e) {
    e.preventDefault();
    $.getJSON(
        this.action + "?callback=?",
        $(this).serialize(),
        function (data) {
            if (data.Status === 400) {
                $(this).find(".email-input").addClass("error");
            } else { // 200
               $(this).find(".response").show();
            }
        });
    });
});
1

There are 1 best solutions below

0
On BEST ANSWER

I'm betting the error comes from $( this ), try caching it:

$('.cm-form').submit(function (e) {

    var $this = $(this);

    e.preventDefault();
    $.getJSON(
        $this.attr('action') + "?callback=?",
        $this.serialize(),
        function (data) {
            if (data.Status === 400) {
                $(".email-input", $this).addClass("error");
            } else { // 200
               $(".response", $this).show();
            }
        });
    });
});