1

我有以下代码,如果用户从下拉列表中选择“其他”,它应该向表单添加一个字段。但是,使用此代码似乎会覆盖下拉列表的值,以便在发布表单时$_POST['enquiry_source']为空。

我已将其缩小到这一行,这导致我在下拉列表中的任何更改上添加该字段时出现问题,而不仅仅是选择了“其他” -

$(field_to_append).insertAfter('#form-field-enquiry_source');

我也试过$('#form-field-enquiry_source').after(field_to_append);,但结果是一样的。

$(function(){

    /** Looks for changes to the enquiry source dropdown */ 
    $('#form-field-select-enquiry_source').live('change', function(){

        /** Check the enquiry source */
        var enquiry_source = $('select[name="enquiry_source"]').val();      

        /**
         * Adds another field to the enquires form when the user selects 'Other' form the enquiry source dropdown
         */
        if(enquiry_source === 'other'){ // The user has selected other as the enquiry source, so lock the form

            var field_to_append = '<div id="form-field-enquiry_source_other" class="form-field float-left">'+
                '<label>Other<span class="required"></span></label>'+
                '<input name="enquiry_source" id="form-field-input-enquiry_source_other" />'+
                '</div>';

            $(field_to_append).insertAfter('#form-field-enquiry_source');

        } else {

            $('#form-field-enquiry_source_other').remove();

        }

    });

});

任何想法是什么导致了这个问题?

4

3 回答 3

1

如果您有一个选择,name = enquiry_source然后您广告一个具有相同名称的输入,则只有一个元素会发布到服务器,在您的情况下,输入字段(仅发布后一个元素),因此您应该为该字段指定一个不同的名称

        var field_to_append = '<div id="form-field-enquiry_source_other" class="form-field float-left">'+
            '<label>Other<span class="required"></span></label>'+
            '<input name="enquiry_source_other" id="form-field-input-enquiry_source_other" />'+
            '</div>';
于 2012-03-28T14:55:44.210 回答
1

我知道这似乎有点离题(但不是)。您可以通过在其中包含这些内容的隐藏 div 来改变您的方法,然后您的问题归结为根据字段显示/隐藏下拉菜单。

关于这一点的好处是在 javascript 缩小时不能缩小长字符串,这样做可以节省更多空间。

if(enquiry_source === 'other'){ // The user has selected other as the enquiry source, so lock the form
        $("#enquiry_source_other").show();
    } else {
        $("#enquiry_source_other").hide();
    }

我觉得这种方法更简单一些

于 2012-03-28T14:56:19.260 回答
1

你在里面插吗?听起来你正在生成一个 html 代码

<form>something</form><input name=enquiry_source>

也许你想要的是 $('#form-field-enquiry_source').append($(field_to_append));

我不知道什么是“#form-field-enquiry_source”。是表格吗?

于 2012-03-28T14:55:05.297 回答