2013-11-20 40 views
1

我有一個輸入字段,只有在選中「Other」選項時纔會顯示。當我取消選中「其他」複選框時,輸入字段會淡出,但我還希望輸入字段可以淡出,而不是取消選中「其他」複選框,然後選中同一組的另一個複選框。因此,除非選中「其他」,否則「其他」輸入字段不可見。我有JavaScript部分工作,但是當我檢查另一個複選框時,「其他」輸入字段保持可見。檢查不同的複選框隱藏輸入字段

HTML

<input type="checkbox" id="residence_check" name="found"/> 
<label for="residence_check"> 
    Residence 
</label> 
<input type="checkbox" id="tradeshow_check" name="found"/> 
<label for="tradeshow_check"> 
    Tradeshow 
</label> 
<input type="checkbox" id="office_check" name="found"/> 
<label for="office_check"> 
    Office Building 
</label> 
<input type="checkbox" id="check_other" value="found_other" name="found"/> 
    <label for="check_other"> 
    Other 
</label> 
<input type="text" id="check_input" placeholder="Other"/> 

的Javascript

$('#check_other').change(function() { 
    if($(this).is(":checked")) { 
     $('#check_input').fadeIn(); 
    } else { 
     $('#check_input').fadeOut('fast'); 
      } 
}); 

回答

0

從我從你的使用情況收集是你不想使用複選框,但單選按鈕。如果是這樣的話,這將是實現你想要什麼好辦法:

http://jsfiddle.net/AeP58/1/

$('input[type=radio]').on('change', function() { //event on all radio buttons 
    if($(this).attr('id') == 'check_other' && $(this).prop('checked')) { 
     $('#check_input').fadeIn(); 
    } else { 
     $('#check_input').fadeOut('fast'); 
    } 
}); 

如果你想複選框,你可以改變一下代碼,並可能會得到你想要的。

+0

我剛剛更改爲輸入[type = checkbox],它的效果很好。謝謝! – user2736472

0

如果你想有一些有趣的複選框,你可以試試這個:

function showHideOtherInput() { 
console.log($(this)[0]==$('#check_other')[0]); 
     var shouldShow=$('[id$="_check"]:checked').length===0 && $('#check_other').prop('checked'); 
     console.log(shouldShow); 
    if(shouldShow) { 
     $('#check_input').fadeIn(); 
    } else { 
     $('#check_input').fadeOut('fast'); 
      } 
} 
$('#check_input').hide(); //since nothing is selected at this point just hide the input 
$('#check_other').change(showHideOtherInput); 
//for each XXXX_check checkbox trigger the show or hide function 
$('[id$="_check"]').each(function(ix,el){$(el).change(showHideOtherInput)}); 

希望這對你的作品。 :)