Skip to content
Advertisement

jQuery addClass when value of hidden input changes dyamically

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

Advertisement

Answer

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');
  };
})();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement