Domanda

This is a jquery question and since i am working with wordpress and options framework in the admin panel i have to hide certain options with a checkbox. The problem is one of the elements is a dropdown menu and it seems that i cannot hide it at the beginning (meaning if i click twice the dropdown disappears as it should) although the code works for the text input. Here is the code:

jQuery('#telephone_hidden').click(function() {

    if (jQuery('#telephone_hidden').attr('checked') ? true : false) {
        jQuery('#section-telephone_dropdown_icons, #section-telephone_number_hidden').show();
    } else {
        jQuery('#section-telephone_dropdown_icons, #section-telephone_number_hidden').fadeToggle(400);
    }
});

I am not very good with jQuery but i think that this should work, or at least there is a better way to this.

Thanks

È stato utile?

Soluzione

An if statement with a ternary statement ... not going to work. Try this:

if (jQuery('#telephone_hidden').prop('checked')){
    jQuery('#section-telephone_dropdown_icons, #section-telephone_number_hidden').show();
} else {
    jQuery('#section-telephone_dropdown_icons, #section-telephone_number_hidden').fadeToggle(400);
}

The .prop('checked') returns a boolean, which I think is what you want to validate. Also, there really isn't a need to use jQuery if you properly set up your libraries to not conflict. You can consolidate it to:

if ($('#telephone_hidden').prop('checked')){
    $('#section-telephone_dropdown_icons, #section-telephone_number_hidden').show();
} else {
    $('#section-telephone_dropdown_icons, #section-telephone_number_hidden').fadeToggle(400);
}

This doesn't seem like much, but over an entire script file you reduce its size and therefore improve its performance. Depending on how big your file is, it can have a huge impact.

Also, noticed you were using the .click event for $('#telephone_hidden'), so rather than query the DOM again, try this:

var $tel = $('#section-telephone_dropdown_icons, #section-telephone_number_hidden');

$('#telephone_hidden').on('click',function() {
    if ($(this).prop('checked')){
        $tel.show();
    } else {
        $tel.fadeToggle(400);
    }
});

The use of $(this) prevents needing to query the DOM for the selector again, and I cache the selector used for the show / fadeToggle, providing another performance boost.

I know this is a long answer, but I figured if I showed the step-by-step process of improvement you could learn and apply it to future jQuery endeavors.

Altri suggerimenti

Try .is()

if (jQuery('#telephone_hidden').is(':checked')) {

or .prop

if (jQuery('#telephone_hidden').prop('checked')){

You can use the is function in conjunction with the checked selector, like so:

if ($('#telephone_hidden').is(':checked')) {
   // ... do something
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top