更改选择输入选择国家?

时间:2010-10-14 19:58:09

标签: jquery

我有一个国家选择字段,允许美国,加拿大和欧洲选择,我们的大多数用户将来自美国/加州,因此我们默认显示省份,但是当用户选择欧洲时,我们希望它从选择更改为一个输入框。我们有

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部分都是正确的,我检查了名称。

4 个答案:

答案 0 :(得分:6)

将其放在$(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。例如,您确定value代码的<select>属性为Europe且资本为E吗?

答案 1 :(得分: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

答案 2 :(得分:1)

我看到您正在使用已定义ID的输入元素替换它们但您的jQuery选择的目标是类.state_d。它应该是#state_d吗?

答案 3 :(得分:1)

您可以使用此功能:

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()
        }));
}