jQuery setting value on hidden input

Myke623

Well-known member
On my form, I have a bunch of my own little toggle buttons that indicate whether these sub-elements are applicable or not, to the main item being edited. This part of the form appears as follows:

form-01.webp
In the above form, only the first sub-element ("ei") is currently applicable which is indicated by both the div class, and the hidden input set to "yes".

These sub-elements are rendered using a div with classes "AppliesYesNo", along with a "yes" or "no" to indicate if the sub-element is applicable or not.

And for the purposes of form submission, there is a hidden input field whose value will change to "yes" or "no" whenever the div is clicked accordingly.

This toggle functionality is done via the following javascript which is registered via the "AppliesYesNo" class:

Code:
XenForo.Foo =
{
    AppliesYesNo: function($handle)
    {
        $handle.on('click', function()
        {
            var $hiddenVal = $('#' + $handle.data('id'));
         
            if ($handle.hasClass('no'))
            {
                $handle.removeClass('no');
                $handle.addClass('yes');
                $hiddenVal.val('yes');
            }
            else
            {
                $handle.removeClass('yes');
                $handle.addClass('no');
                $hiddenVal.val('no');
            }
        });
    }
};

XenForo.register('.AppliesYesNo', 'XenForo.Foo.AppliesYesNo');

So on click, the yes/no class of the div is toggled, and the hidden input value is set accordingly, and this all works fine for the first time.

However, when I attempt to re-edit the same entry again, the hidden input value will cease to toggle. Specifically the lines that change the $hiddenVal.val() have no effect, even though the div class will still toggle. If I reload the entire page and open the form, it will work as expected, but again, only for the first time.

The screenshot below shows how the two elements get out of sync:

form-02.webp
After a form submission, and editing the same item again, subsequent clicks on the div will only toggle the class value and not the hidden input.

I suspect that there's may be more than one element with the same id floating around the system, but I'm unsure as to how to troubleshoot that.

Any ideas as to how to resolve this would be greatly appreciated.
 
Last edited:
Code:
XenForo.Foo =
{
   AppliesYesNo: function($handle)
   {
     $handle.on('click', function(){
       var $e = $(this),
         $hiddenVal = $e.find('#' + $e.data('id'));
     
       if ($e.hasClass('no')){
         $e.removeClass('no').addClass('yes');
         $hiddenVal.val('yes');
       } else {
         $e.removeClass('yes').addClass('no');
         $hiddenVal.val('no');
       }
     });
   }
};

XenForo.register('.AppliesYesNo', 'XenForo.Foo.AppliesYesNo');
Try something like this.
 
Top Bottom