Essam Al Joubori
Essam Al Joubori

Reputation: 36

Trigger event on submit

In a newsletter sign-up form, I would like to make the email disappear after the end user hits enter. I have already added JS to hide and unhide the placeholder text.

The code:

<form id="form" action="https://xxxx.com/subscribe/post-json?u=xxx&id=xx&c=?" method="GET">
  <input type="hidden" name="u" value="xxx">
  <input type="hidden" name="id" value="xxx">
  <input id="email" type="EMAIL" autocapitalize="off" autocorrect="off" name="MERGE0" id="MERGE0" size="25" placeholder= "Type your email and press enter">
  <p id="response"></p>
</form>

And the JS:

<script >

 var text = document.getElementById("email");  

    text.onfocus = function() {
        if ( text.placeholder == "Type your email and press enter") {
            text.placeholder = "";
        }      
    };    
    text.onblur = function() {
        if ( text.placeholder == "") {
            text.placeholder = "Type your email and press enter";
        }
    };
</script>

I tried to create a function to trigger the event but it still didn't work:

 function checkEnter(event)
{
   if (event.keyCode == 13) {text.placeholder = "cool";}
};

Could you all see what's wrong with my code?

Thank you.

Upvotes: 0

Views: 129

Answers (2)

Essam Al Joubori
Essam Al Joubori

Reputation: 36

I have integrated the code below with the mailchimp form and got the desired results:

var paragraph = document.getElementById('response');

       $('#form').submit(function(e) {
       var $this = $(this);

       $.ajax({
               type: "GET", // GET & url for json slightly different
               url: "https://xxxxx.com/subscribe/post-json?u=xxxx&id=xxx&c=?",
               data: $this.serialize(),
               dataType    : 'json',
               contentType: "application/json; charset=utf-8",
               error       : function(err) { alert("Could not connect to the registration server."); },
               success     : function(data) {
                   if (data.result != "success") {
                       paragraph.innerHTML = data.msg;
                       text.placeholder = "Oopsy daisy! Error :-("; 
                       form.reset();
                    } else {
                       paragraph.innerHTML = data.msg;
                       text.placeholder = "Thanks so much!"; 
                       form.reset();
                       }
                    }
                  });
                  return false;
                });

Upvotes: 0

Isabeau Bergeron
Isabeau Bergeron

Reputation: 106

You need to add a event listener for the enter key. You could remove your function checkEnter and use this instead:

document.querySelector('#email').addEventListener('keypress', function (e) {
  var key = e.which || e.keyCode;
  if (key == 13) {
    text.placeholder = "cool";
  }
};

Upvotes: 1

Related Questions