使用JS.insertAfter()时丢失PHP$_POST值

PHP $_POST value being lost when using JS .insertAfter()

本文关键字:PHP POST insertAfter JS 使用      更新时间:2023-09-26

我有以下代码,如果用户从下拉列表中选择"其他",它应该会向表单添加一个字段。但是,使用此代码似乎会覆盖下拉列表的值,因此在发布表单时,$_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();
        }
    });
});

你知道是什么导致了这个问题吗?

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

        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>';

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

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

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

我不知道什么是"#form-field-quiry_source"。是表格吗?

我知道这似乎有点偏离主题(但事实并非如此)。您可以通过创建一个隐藏的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();
    }

我觉得这种方法有点简单