2012-06-14 47 views

回答

1

Fixed Working Version

首先,你需要調用.val()就像是指出。

var val = $('#event_options_id option:selected').val(); 

然後根據選擇您使用您需要使用parseInt()在VAL使它一些像這樣

if ($.inArray(parseInt(val,10), arr) > -1) { 

您還定義你的陣列時,有一個額外的逗號。

完整的工作守則

$(document).ready(function() { 

    $('#event_options_id').change(function() { 

     $('.container_add_form').remove(); 

     var val = $('#event_options_id option:selected').val(); 
     var arr = [3, 4]; 

     if ($.inArray(parseInt(val,10), arr) > -1) { 
      $('<input type="hidden" name="age_required" id="age_required" value="yes" /><div class="container_add_form"><p class="text_content">Please enter your age for grouping purposes.<br /><input name="age" type="text" id="age" size="3" /></p></div>').fadeIn('slow').appendTo('.add_form'); 
     } 
    }); 
});​ 
+1

這樣做。感謝您的幫助 – user1403688

+0

'$('#event_options_id選項:選中')'已經結束了。 – Gabe

2

jsFiddle

更改此:

var val = $('#event_options_id option:selected').html(); 

要:

var val = $('#event_options_id').val(); 
+0

+1,但似乎並沒有解決問題。 – undefined

+0

是的,它確實解決了這個問題。點擊鏈接。 – Gabe

+0

不錯,也許我不知道是什麼問題。 – undefined

0

1)使用.val()代替.html()獲得期權的價值。

2)您正在比較字符串值與數組中的數字,這將始終失敗。

http://jsfiddle.net/kCLxJ/4/

var val = $('#event_options_id option:selected').val(); 
var arr = ['3', '4']; 
-1

我更新了你的代碼:http://jsfiddle.net/kCLxJ/7/

$(document).ready(function() { 

    $('#event_options_id').change(function() { 

     $('.container_add_form').remove(); 

     // you used .text() but should've used .val() 
     var val = $('#event_options_id option:selected').val(); 
     var arr = [3, 4]; 

     /* 
      another problem was that you didn't parse the value into an integer 
      but you were comparing the value to an array of integers 
     */ 
     if ($.inArray(parseInt(val), arr) > -1) { 
      $('<input type="hidden" name="age_required" id="age_required" value="yes" /><div class="container_add_form"><p class="text_content">Please enter your age for grouping purposes.<br /><input name="age" type="text" id="age" size="3" /></p></div>').fadeIn('slow').appendTo('.add_form'); 
     } 
    }); 
}); 
+0

爲什麼這個答案已經被低估? – undefined

+0

也許是因爲我沒有按照StackOverflow的回答規則。我在StackOverflow外部創建了一個只能通過訪問鏈接訪問的答案。通常,鏈接是附加信息的資源,而不是答案本身。答案的文本應該發佈在StackOverflow上。因爲我看到別人給出了很好的答案,我沒有打擾更新/完成我的答案。 –

0

更改這些行。

var val = $('#event_options_id option:selected').val(); 
    var arr = ["3", "4"]; 

要獲得組合框的值,必須使用'val()'而不是'html()'。 而你必須將數組的元素更改爲字符串。 變量val是一個字符串。 inArray將嘗試將該元素查找爲字符串,而不是整數。