2012-10-02 24 views
0

我有兩個複選框組,我最終需要其中一個影響另一個的輸出(可見性)。這是我的小提琴。基於值的同步複選框可見性

http://jsfiddle.net/kEKYw/1/

所以,從第一輸入(int值)的值應與來自第二複選框組(當前隱藏)的輸入值,然後顯示這些基於該選擇。我覺得我相當接近,但任何向正確的方向推動都會有很大的幫助。謝謝!

+0

您的例子並不清楚,我既是複選框組包含完全相同的值。無論哪種方式,你的jQuery選擇器沒有找到一個元素,因爲你沒有任何元素的ID爲'wood_types'。您可能想要使用啓動或包含選擇器:http://api.jquery.com/category/selectors/。 –

回答

1

修改了你的代碼。查看關於代碼的評論。

DEMO:http://jsfiddle.net/kEKYw/3/

$("#wood_typeschecklist input").change(function() { 
    var destEl = this.id.split("-"); 
    //a. Changed selector to look for starts with selector as the 
    //checkbox value returned is wood_type-<number> 
    //which doesn't match any existing id 

    //b. `.split` splits the string when it matches its 
    //separator and so it was returning 3 tokens not 2 (in,wood_types,126) 
    var $matchingElem = $("li[id^=" + destEl[1] + '-' + destEl[2] + "]", $("#acf-wood_species_availability")); 
    ($(this).attr("checked") !== undefined) ? $matchingElem.show() : $matchingElem.hide(); 
}); 
+0

非常酷 - 將測試並回報。非常感謝你 – Zach

+0

正是我在找什麼。我建立了http://pastebin.com/mXbVgkK9關於你提供的內容,除了檢查它們是否已經在頁面加載中被選擇 - 這也很好。再次感謝!! – Zach

1

我相信this fiddle是你在找什麼

// start off by hiding the second options 
$("#acf-wood_species_availability li").hide(); 

//add a click method to the inputs 
$("#wood_typeschecklist input").click(function() { 
    //verify that it's checked, if so, show the other input of the same value (and check it also) 
    if ($(this).is(':checked')) { 
     $('#acf-wood_species_availability input[value="' + $(this).val() + '"]').attr('checked', true).parents('.popular-category').show(); 
    } 
    //if it's unchecked, hide the other input and uncheck this one 
    else { 
     $('#acf-wood_species_availability input[value="' + $(this).val() + '"]').attr('checked', false).parents('.popular-category').hide();        
    } 
}); 

//now let's add click methods to the other checkboxes in case user clicks on them, if so, we hie this checkbox and uncheck the other one. 
$("#acf-wood_species_availability input").click(function() { 
    $(this).attr('checked', '').parents('.popular-category').hide(); 
    $('#wood_typeschecklist input[value="' + $(this).val() + '"]').attr('checked', false); 
}); 
+0

欣賞答案,@Vega剛剛來到這裏。再次感謝! – Zach

+0

的確如此,但我認爲你想讓用戶可以雙向使用。這就是爲什麼我的代碼有點複雜!乾杯! –