防止序列化输入

问题描述 投票:3回答:1

我有选择选项框。

<form class="i-hate-u">
   <select class="helloMoto" name="helloMoto">
      <option value="">Select...</option>
      <option value="-1">Other</option>
   </select>
</form>

当最终用户选择“其他”选项时,文本输入如下所示:

$('.helloMoto').on('change', function() {
      if ($(this).val() == '-1')
            $(this).hide();
            var input_name = $(this).attr('name');
            var input = '<div class="input-group">' +
                             '<input type="text" class="form-control" name="'+input_name+'" placeholder="Type other.">' +
                              '<span class="input-group-btn">' +
                                     '<button class="btn btn-primary" onclick="removeSelectOther(this);"><i class="la la-close"></i></button>' +
                              '</span>' +
                        '</div>';

            $(this).parent().append(input);
});

最后,当最终用户单击“保存”按钮时,我会像这样序列化整个表单:

var data = $('.i-hate-u').serialize();

如您所见,如果用户选择了其他选项,则输入显示为同名。如果用户选择其他选项,我想删除。有没有办法,如果序列化的值具有相同的名称,跳过第一个或-1。

jquery html
1个回答
1
投票

在序列化之前,检查valuehelloMoto是否为-1,如果是,则禁用<select>(在表单提交上):

if($('select[name="helloMoto"]').val() == -1)
{
    $('select[name="helloMoto"]').attr('disabled', true);
}

或者你可以尝试,只需排除helloMotowhile序列化:

if($('select[name="helloMoto"]').val() == -1)
{
    var data = $('input[name!=security]', $('.i-hate-u')).serialize();
}else 
{
    var data = $('.i-hate-u').serialize();
}
© www.soinside.com 2019 - 2024. All rights reserved.