更改选择输入选择国家/地区?

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

jQuery('select.country_d').change(function(){ if($('select.country_d').val() == "Europe") $('.state_d').replaceWith(''); }); jQuery('select.country_o').change(function(){ if($('select.country_o').val() == "Europe") $('.state_o').replaceWith(''); }); 

但它似乎没有起作用。 html部分都是正确的,我检查了名称。

把它放在$(function())这样你的.change()函数就会被页面加载绑定:

 $(function() { $('select.country_d').change(function() { if ($(this).val() == 'Europe') $('.state_d').replaceWith(''); }); $('select.country_o').change(function(){ if($(this).val() == 'Europe') $('.state_o').replaceWith(''); }); } ); 

如果这不起作用,那么你应该发布你的HTML。 例如,您确定标签的value属性是具有大写字母E的Europe吗?

以下是我这样做的版本。 评论中提到了一些警告。 随意调整以删除警告或根据您的应用程序的假设进行调整。 假设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 = $ '' # Copy attributes for attr in ['id', 'className', 'name', 'required'] text.attr attr, $_.attr(attr) # Replace select with text area $_.replaceWith text 

我看到你用已定义ID的输入元素替换它们但是你的jQuery选择是针对类.state_d 。 它应该是#state_d吗?

你可以使用这个function:

 function transformSelectIntoInput(elementSelector){ var $el = $(elementSelector); $el.replaceWith($('').attr({ type: 'text', id: $el.attr('id'), name: $el.attr('name'), class: $el.attr('class'), value: $el.val() })); }