S.Oruc S.Oruc - 1 month ago 6
CSS Question

jQuery each and change combined

I want to combine

each
and
change
with jQuery.

This is my code:

$( document ).ready(function() {
$('.doetmee').each(function() {
var thisval = $(this).val()

if(thisval == 'ja')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',false);
}
else
{
$(this).parent().parent().find('.facebookadv').attr('disabled',true);
$(this).parent().parent().find('.facebookadv').val('');
}

$('.doetmee').change(function(){
if(thisval == 'ja')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',false);
}

if(thisval == 'nee' || thisval == 'leeg')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',true);
$(this).parent().parent().find('.facebookadv').val('');
}
});
});
});


It only changes 1 time and after that it doesn't work.

How can I make sure it works everytime I make a change?

I have tried many things that I could find on stackoverflow or google but without success.

enter image description here

If the value is
leeg
or
nee
the select on facebook must be disabled.

Answer

You need to make each and change register the same function.

$( document ).ready(function() {

    var updateFields = function() {
        var thisval = $(this).val()

        if(thisval == 'ja')
        {
            $(this).parent().parent().find('.facebookadv').attr('disabled',false);
        } else {
            $(this).parent().parent().find('.facebookadv').attr('disabled',true);
            $(this).parent().parent().find('.facebookadv').val('');
        }
    };

    $('.doetmee').each(updateFields);
    $('.doetmee').change(updateFields);

});

In the above example, the function is stored in the variable updateFields (so the code is only written once) and is then registered to both each and change.

Comments