2010-10-14 124 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() 
     })); 
}