2013-10-31 32 views
0

我有以下用於顯示/隱藏條件表單域(包含在tr#other-employer內)的jQuery代碼。這工作正常,一旦頁面加載和選項更改。在加載時顯示一個條件表單域,當預先選擇時

我想這樣做,使得條件字段顯示何時加載頁面,並且在#employer的下拉列表中選擇的選項被預先選擇(這是用PHP完成的)。

我試過刪除$('tr#other-employer').hide();,但是這樣就顯示了加載條件字段,無論下拉字段是否是其他字段。

一個簡單的示例頁面在這裏:http://brenda.upreach.org.uk/beta/form.php

$(document).ready(function() { 
    $('tr#other-employer').hide(); 
    $('#employer').change(function() { 
     if ($(this).val() == "Other") { 
      $('tr#other-employer').fadeIn(); 
     } else { 
      $('tr#other-employer').hide(); 
     } 
    }); 
}); 

任何幫助,不勝感激!

回答

2

您可以添加如下條件來檢查選擇框的狀態並執行必要的操作。

$(document).ready(function() { 
    $('tr#other-employer').hide();  



    /*********************************/ 

     if($("select#employer").val() == "Other") 
     {   $('tr#other-employer').fadeIn(); } 

    /*********************************/ 

$('#employer').change(function() { 
if ($(this).val() == "Other") { 
$('tr#other-employer').fadeIn(); 
} else { 
$('tr#other-employer').hide(); 
} 
}); 
}); 

您還可以設置從jQuery的使用

$( 「#選擇僱主」)選擇框的默認選項VAL( 「其他」)。

+0

這正是我期待的!謝謝! – user2761030

0

我不確定我完全理解了這個問題,但是如果您正在尋找此代碼提供的相同功能,但沒有要求採取措施,那麼只需刪除.change()函數,然後換出this該ID:

$(document).ready(function() { 
    $('tr#other-employer').hide(); 
    if ($('#employer').val() == "Other") { 
     $('#other-employer').fadeIn(); 
    } 
}); 

編輯:

以上應該工作,給出下面的HTML(我已經移除這兩個表的代碼,爲了簡化說明):

<form> 
    <select id="#employer"> 
     <option value="Foo">Foo</option> 
     <option value="Other" selected="selected">Other</option> 
    </select> 
    <select id="#other-employer"> 
     <option value="Foo">Bar</option> 
    </select> 
</form> 

鑑於上述代碼,只有在加載時預先選擇了「其他」選項時,#other-employer下拉菜單纔會顯示。

+0

感謝@Nathan雖然代碼並沒有引用似乎工作...我在這裏用舊代碼做了一個快速示例頁面:http://brenda.upreach.org.uk/beta/form。 PHP我試圖讓它顯示條件字段,如果其他預選 – user2761030

+0

所以你想實現的是: 如果一個字段是預先選擇,顯示另一個字段? –

+0

你接受的答案和我的一樣,順便說一句。無論如何:/唯一的區別是我刪除了我認爲隱含的「變化」情況。上面的代碼應該工作不管,特別是因爲接受的答案是具有完全相同的更改。 –

相關問題