1

I have a contact form that sends a value to a hidden input on successful completion of the sendmail function. I want to detect this value change and then use it to apply a class to a div/paragraph.

I asked a similar question recently and I'm aware that this requires the script to continually check the doc after DOM is loaded but even after adding .change() it just doesn't seem to want to add the class.

Here's the jQuery:

$(document).ready(function() {
   $("#acf_success_sent").change(function(){
    if ($("#acf_success_sent").val() == "1"){
     $("#acf_verified").addClass('gone');
     }
   });

 });

any help would be great. here's a link to a test version of form in case you're interested, everything works except the verified symbol doesn't disappear after a successful send http://seeshell.me/forms/contact.php

1 Answer 1

2

There'll be no "change" event fired when code updates the value of your <input> element, so the handler you've registered won't run. What you could do however is fire "change" from a watchdog:

var watchdog = setInterval(function() {
  if ($('#acf_success_sent').val() !== originalValue)
    $('#acf_success_sent').trigger('change');
}, 100);

How you set up "originalValue" depends on your application. You could, for example, keep a separate ".data()" value, and watch for whenever your saved value differs from the current "value" attribute. Or you could keep the value in a closure variable:

var watchdog = (function() {
  var $acfSuccessSent = $('#acf_success_sent'), cachedValue = $acfSuccessSent.val();
  return function() {
    if (cachedValue !== $acfSuccessSent.val())
      $acfSuccessSent.trigger('change');
  };
})();
Sign up to request clarification or add additional context in comments.

6 Comments

originalValue will always be 0 unless form is sent so I can just put !== "0") i guess?! ill try it out. thank you
Yes, if you know the original value, and you only care about changes from that, then you can simplify. Also, of course, to get even simpler, you could always do all the work inside the timer routine itself :-)
it worked 1st time. Thank you very much, buying a jQuery book right now, I'm fed up of being so lame.
Good news: O'Reilly is running a sale on JavaScript books (maybe US-only unfortunately ...) (also, sorry about that, person from 2012 :-)
or if ($('#acf_success_sent').val() !== $('#acf_success_sent')[0].defaultValue)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.