【问题标题】:Struggling to get multiple input fields value with the same name in Spring Boot努力在Spring Boot中获取多个具有相同名称的输入字段值
【发布时间】:2019-05-11 01:08:12
【问题描述】:

My input field

我的问题是如何从 Name="phone" 字段中获取所有值

JS

<script>
    $(function(){

        $(document.body).on('click', '.changeType' ,function(){
            $(this).closest('.phone-input').find('.type-text').text($(this).text());
            $(this).closest('.phone-input').find('.type-input').val($(this).data('type-value'));
        });

        $(document.body).on('click', '.btn-remove-phone' ,function(){
            $(this).closest('.phone-input').remove();
        });


        $('.btn-add-phone').click(function(){

            var index = $('.phone-input').length + 1;

            $('.phone-list').append(''+
                '<div class="input-group phone-input">'+
                '<input type="number" name="phone" class="form-control" placeholder="(999) 999 9999" />'+
                '<span class="input-group-btn">'+
                '<button class="btn btn-danger btn-remove-phone" type="button"><span class="glyphicon glyphicon-remove"></span></button>'+
                '</span>'+
                '</div>'
            );

        });

    });</script>

HTML

<div class="col-sm-10">

                        <div class="phone-list">

                            <div class="input-group phone-input">
                                    <span class="input-group-btn">
                                    </span>
                                <input type="number" name="phone" class="form-control" placeholder="(999) 999 9999"  required=""/>
                            </div>

                        </div>


                        <button type="button" class="btn btn-success btn-sm btn-block btn-add-phone"><span class="glyphicon glyphicon-plus"></span> Add Phone</button>
                    </div>

控制器

   @PostMapping("/applicant")
   public String saveApplicantToDb(
       @Valid @ModelAttribute Applicant applicant, 
       @RequestParam("phone") int[] phone
   ) {
        if (phone!= null)
        System.out.println(phone.length);

        _applicantRepository.save(applicant);

        return "applicant";
    }

【问题讨论】:

  • 请将您的代码作为文本粘贴到此处,而不是图像。很难做到。
  • 已编辑如果你应该提供更多代码让我知道请帮助大家)真的很感激))
  • @Aliy 请编辑答案。我看不到 HTML。
  • 编辑@Mureinik
  • 找到答案了吗?我有一个类似的问题。 @Aliy

标签: java spring spring-boot model-view-controller


【解决方案1】:

您正在使用具有相同名称“电话”的多个输入数字字段,这是正确的,这没有问题,它应该反映在输入@Param(“电话”)中,但您必须确保电话输入必须是整数类型,例如您的占位符完全不正确 (999) 999 9999。新添加的电话也不是整数。所以确保它们是整数

【讨论】:

  • 我已经找到了解决这个问题的方法,感谢回复
  • 你是对的,它正在向我发送 String[] 类型的数组
【解决方案2】:

问题是名称应该与您的模型属性匹配 但是我期待从视图中显示 int[] 类型的数组,但它向我发送了 String[] 类型的数组问题已解决,并且还确保您的 JS 代码正确填充您的输入字段 [尤其是 name='field_name'] 应该与属性匹配你的模型。在浏览器上检查您的 -> 检查并折叠 div 并查看输入字段名称

【讨论】:

    猜你喜欢
    • 2017-04-08
    • 2021-12-18
    • 2013-07-02
    • 2021-05-11
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    相关资源
    最近更新 更多