简体   繁体   中英

How can I send an array of values from the inputs to the controller

I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.

Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.

<form id="selectform" th:object="${systemIdListForm}" th:action="@{/myController}" method="get">
    <div class="box-body">
        <label>System Id:</label>
        <div id="fields">
            <div class="form-group col-md-1">
                <input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
            </div>
        </div>
        <a id="addMore" href="#"><i class="fa  fa-plus"></i><span>Add</span></a>
    </div>
    <div class="box-footer">
        <button type="submit" class="btn btn-primary">Select</button>
    </div>
</form>



<script  type="text/javascript">
/*<![CDATA[*/
 $(document).ready(function () {
     $("#addMore").click(function() {
     var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
     $('#fields').append(html);
     });

     $("#selectform").submit(function(){
         var values = $(this).serialize();
     });
 });
/*]]>*/
</script>

At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.

Any help is much appreciated

What data type have you used in Model ? Make sure you have taken String [] for that field. If not taken String [] then use that and let me know whether it works or not.

Also you can take help of below code.It is for your case only.

$("#selectform").submit(function (event) {

        // form redirect stop
        event.preventDefault();
        var status = jbf.form.validate('#selectform');
        if (!status) {
            return;
        }


        // get form data
        var data = {};
        data["enrollmentNumber"] = $("#enrollmentNumber").val();
        data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();

        var url = "/yourURL";

        $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(data),
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                var message = response.message;
                //success notification
                if(response.success === true){
                    alert(message);

                }else{
                    error(message);
                }

            },
            error: function (e) {
                console.log("ERROR: ", e);
                error("Add failed");
            }
        });

    });

I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.

 <form id="selectform" th:object="${myEntiry}" th:action="@{/crops/singlecroplabeloffinsp/list/1}" method="get">

    <input class="form-control" id="systemIdList" th:field="*{systemIds}"  type="hidden"/>

    <div class="box-body">
        <label>System Id:</label>
        <div id="fields">
            <div class="form-group col-md-1">
                <input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
            </div>
        </div>
        <a id="addMore" href="#"><i class="fa  fa-plus"></i><span>Add</span></a>
    </div>
    <div class="box-footer">
        <button type="submit" class="btn btn-primary">Select</button>
    </div>
 </form>

 ...

  $("#selectform").submit(function(){

      //get all the system ids
      var x = document.getElementsByName("systemIdInput");
      var systemIds = [];

      for (i = 0; i < x.length; i++ ) {
          if (x[i].type ='text') {
              systemIds.push(x[i].value);
          }
      }

      $("#systemIdList").val(systemIds);
      this.submit();
  });

Added to the entity with getter & setter:

@Transient
private List<Integer> systemIds;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM