0

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

2 Answers 2

2

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");
            }
        });

    });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, I had ajax in mind but I was trying to avoid it in this case. I found a way of getting the list of input values back in the controller.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.