2013-10-22 36 views
0

如果選擇「其他」選項,我嘗試顯示一個文本框時我試圖創建一個選項下拉菜單,並且卡住了。jQuery:如果選擇了一個選項,則更改一個css值

有我有:

<span id="con-country"><label for="country">Country: </label> 
<select name="country" required="required"> 
<option value="usa">United States</option> 
<option value="uk">United Kingdom</option> 
<option id="other" value="other">Other</option> 
</select> 
</span> 

<span id="con-specify"> 
<label for="specify">Specify: </label> 
<input type="text" name="specify" id="c-specify" required="required"></input> 
</span> 

CSS:

#con-specify{ 
    margin-left: 50px; 
    display: none; 
} 

簡單吧?問題是,我不知道該怎麼辦的代碼jQuery中

所以,如果用戶在菜單中選擇其他,那麼應該出現文本框,我該怎麼做?

+0

你嘗試過什麼?此外,將這個問題看作是多個問題可能會有所幫助:「如何在用戶選擇某個選項時執行某些操作?」,「如何檢查選擇哪個選項?」,「如何獲取HTML元素?」 ,「如何更改元素的CSS?」 – Zhihao

回答

1

嘗試

//dom ready handler 
jQuery(function($){ 
    //change event handler for the select 
    $('select[name="country"]').change(function(){ 
     //set the visibility of the specify element based on the value of select 
     $('#con-specify').toggle(this.value == 'other') 
    }).change();//fire the change event so that the initial visibility is set 
}) 

演示:Fiddle

瞭解更多關於每種方法http://api.jquery.com/

0

如果你已經使用jQuery,只需使用$('#con-specify').show()$('#con-specify').hide()

0

你會想在html頭部添加一個jQuery鏈接:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> 

下拉菜單中應該有一個ID(即:國家)。

然後你的JavaScript將是這個樣子:

window.onload = function() { 
     $('#con-specify').hide(); 

     $('#country').change(function(){ 
     if($(this).val() == 'other') { 
      $('#con-specify').show(); 
     } else { 
      $('#con-specify').hide(); 
     } 
     }); 
    }; 
相關問題