2012-03-04 74 views
-1

我想打開一個選擇框顯示一個輸入框,當某些選項被選中。選擇框打開輸入框jQuery

這裏是我的代碼:

$("document").ready(function() { 
    $('input.other').hide(); 
    $('#amount').change(function() { 
     // var val = $(this).find('option:selected').text(); 
     //alert(val); 
     var selectedValue = $(this).find(":selected").val(); 
     //alert(selectedValue); 
     if($(this).selectedValue == '25.00') { 
      // only if the radio button has a dob-field 
      $('input.other').show();// show only the following first 
     } 
    }); 
}); 
+0

細說您的問題 – 2012-03-04 17:28:19

+0

有在你的代碼中的許多錯誤。它是'$(document).ready(function(){})'。它不是'if($(this).selectedValue == '25 .00')'but if(selectedValue == '25 .00')'...和'$('input.other')。show()'just否定你在第二行做的事。 – 2012-03-04 17:33:11

+0

你可以嘗試改寫第一句話嗎?目前的形式沒有多大意義。 – 2012-03-04 18:16:15

回答

2

您可以針對內選定option#amount元素直接使用下面的選擇器,並找到它的值並在if語句內進行比較。

與問題的代碼的問題是$(this).selectedValue,其中$(this)指的是#amount而不是optionselectedValue是一個變量,應該直接使用,但它是不是真的有必要在這裏使用一個變量,它完全可讀,並且可以直接處理if語句中的所有內容。

$('input.other').hide(); 
$('#amount').on('change', function(){ 
    if($(':selected', this).val() == '25.00') { 
     $('input.other').show(); 
    } 
}); 
+0

您可能想要添加一些解釋他的錯誤以及您的代碼的作用。這樣你的答案也可以用於未來的開發者。 – 2012-03-04 18:07:20

+0

@OctavianDamiean - 開心:-) – adeneo 2012-03-04 18:23:37

+0

絕對如此。謝謝! – 2012-03-04 18:27:18

1

使用selectedValue檢查不$(this).selectedValue

if(selectedValue == '25.00') { // only if the radio button has a dob-field 
$('input.other').show();// show only the following first 
} 

下面是一個完整的工作片段

$(document).ready(function() { 
    $('input.other').hide(); 
     var selectedValue = $(this).find(":selected").val(); 
     if(selectedValue == '25.00') { 
      // only if the radio button has a dob-field 
      $('input.other').show();// show only the following first 
     } 
    }); 
}); 
+0

當文檔加載其他類的輸入框時將顯示您的代碼。 – user1235905 2012-03-04 17:50:49

+0

@ user1235905,那不是你的代碼。我不想超出問題的範圍 – Starx 2012-03-04 23:40:38

1

您可以在SELECT直接使用.val()不是選擇:selectedOPTION的(假設#amountSELECT元素):

var input = $('input.other').hide(); 
$('#amount').change(function() { 
    if($(this).val() == '25.00') { 
     input.show(); 
    } 
}); 

演示:http://jsfiddle.net/bj6MJ/

加了:假設如果用戶選擇了「25」以外的其他內容,則需要再次隱藏它.00" ,你可以使用toggle()

var input = $('input.other').hide(); 
$('#amount').change(function() { 
    input.toggle($(this).val() == '25.00'); 
}); 

演示:http://jsfiddle.net/bj6MJ/1/