2010-10-14 129 views
2

我有一個允許美國和加拿大和歐洲選擇的國家選擇字段,我們大多數用戶將來自美國/加利福尼亞州,所以我們默認顯示省份,但是當用戶選擇歐洲時,我們希望它從選擇更改爲輸入框。我們有更改選擇輸入選擇國家?

jQuery('select.country_d').change(function(){ 
    if($('select.country_d').val() == "Europe") 
    $('.state_d').replaceWith('<input type="text" name="state_d" id="state_d">'); 
}); 

jQuery('select.country_o').change(function(){ 
    if($('select.country_o').val() == "Europe") 
    $('.state_o').replaceWith('<input type="text" name="state_o" id="state_o">'); 
}); 

但它似乎並沒有工作。 html部分都是正確的,我檢查了名稱。

+1

我可以看到選擇框HTML? – Stephen 2010-10-14 20:02:54

回答

4

把它放在一個$(function())所以你.change()功能綁定在頁面加載內:

$(function() 
{ 
    $('select.country_d').change(function() 
    { 
     if ($(this).val() == 'Europe') 
     $('.state_d').replaceWith('<input type="text" name="state_d" id="state_d">'); 
    }); 

    $('select.country_o').change(function(){ 
     if($(this).val() == 'Europe') 
     $('.state_o').replaceWith('<input type="text" name="state_o" id="state_o">'); 
    }); 
} 
); 

如果不工作,那麼你應該張貼您的HTML。例如,您確定您的<select>標記的value屬性的值爲Europe,並且大寫字母爲E?

1

我看到你用ID定義的輸入元素來替換它們,但你的jQuery選擇是針對類.state_d。應該是#state_d

2

下面是我做這個的版本。評論中提到了一些警告。隨意調整,以消除警告或調整您的應用程序的假設。假設jQuery和用coffeescript編寫,但很容易改變爲普通o'JavaScript。

$ = jQuery 

# Will monitor select fields. If an "Other" option is selected will turn 
# the field into a text field allowing them to enter their custom value. 
# 
# I'm not leaving a way to change back. Since ad-hoc values are allowed I 
# figure if they want a predefined value they can refresh or just type it in. 
# 
# I try to copy all the relevant attriubtes so that the new text field 
# really replaces the original. Would be nice if DOM provided a way to 
# copy all attributes that are available on both elements. Add any missing as 
# I really just copied the ones I am using. 
# 
# Currently it will change any select with an "Other" option. This is probably 
# the most likely thing to change (maybe require a data- attribute to indicate 
# the other option is avaialble). But for now I like the simplicity of just 
# adding the "Other" value to the select options. 
# 
# Any event handlers attached to the old element are not transfered. 
$(document).on 'change', 'select', -> 
    $_ = $ @ 

    return unless $_.val() == 'Other' 
    text = $ '<input type="text" placeholder="Other">' 

    # Copy attributes 
    for attr in ['id', 'className', 'name', 'required'] 
    text.attr attr, $_.attr(attr) 

    # Replace select with text area 
    $_.replaceWith text 
0

您可以使用此功能:

function transformSelectIntoInput(elementSelector){ 
    var $el = $(elementSelector); 

    $el.replaceWith($('<input />').attr({ 
     type: 'text', 
     id: $el.attr('id'), 
     name: $el.attr('name'), 
     class: $el.attr('class'), 
     value: $el.val() 
     })); 
}