Search code examples
javajavascriptspring-mvcmodelattributespring-form

Spring form changed value in not getting reflected in ModelAttribute


I have the following form

<form:form id="form" name="form" target="dummyHiddenForm"  method="post" commandName="myForm" >

            <span class="container">
                <label>TestKey</label>
                <span class="container-right">
                    <form:input path="key" id="key" cssClass="text" maxlength="200" cssStyle="width:60%" disabled="true"/>
                    <input type="button" class="refreshIcon" style="width:auto;" onclick="javascript:refreshKey()" />
                </span>
            </span>

    <span style="width:auto; padding-left: 30%; padding-bottom: 4%; text-align:center; float:right; clear:both;">
        <input type="button" class="button" style="width:auto;" value="Submit" onclick="javascript:submitForm()"/>
    </span> 

</form:form>

<iframe id="dummyHiddenForm" name="dummyHiddenForm" style="display:none;" ></iframe>

In GET request for above page containing form I am setting some default value for each variable of object myForm and key is set to value "". and my java script function for refreshKey() is

function refreshKey(){
    document.getElementById('key').value = generateKey() ; 
}

This method correctly works and onclick sets new key in the input text fields.

on click of submit button I am submitting the form using java script

function submitForm(){
        var formVar = document.forms["form"];
        formVar.action = "/test.htm";
        formVar.submit();
}

But in my controller I get the same default value "" for key irrespective of the the actual value of the input field.

I tried using javascript alert and .value I can see the changed value but the value does not change in actual DOM (at least when I do inspect element from firefox it still shows value="").

I need to get the changed value when the form is submitted. Any suggestions what is going wrong?


Solution

  • Figured out an workaround. The problem was arising due to disabled property i.e disabled="true". Though java script has acess and can modify the value attribute of the input it is not reflected when the spring form is submitted. There was no problem with model attribute binding which I suspected in the begining. Works fine with the disabled attribue turned off.

    However if you still want to make your input field uneditable there is another property readonly which you can set to true. Change the value with javascript and the value is reflected back in the model attribute on form submit.

    <form:input path="key" id="key" cssClass="text" maxlength="200" cssStyle="width:60%" readonly="true"/>