I have a problem with giving the <form:textarea />
tag a default value.
When I created a JSP file as follows:
<form:textarea path="Content" id="my-text-box" />${content}
JSP parser translates the above line to:
<textarea id="my-text-box" name="Content"></textarea>third hello world!
Also, giving the value
attribute does not work.
<form:textarea value="${content}" path="Content" id="my-text-box" />
JSP gives me as HTML output:
<textarea id="my-text-box" name="Content" value="third hello world!"></textarea>
You can see the <textarea>
tag does not have the value
attribute.
How can I pass a default value to <form:textarea>
tag?
Thank you in advance.
The Spring form tags are for data binding (e.g. your model attributes are bind to the form via path
attribute of the form). If you need to specify defaults, then set the Content
attribute of the ModelYouArePassingToView
to the desired default value in the controller before it gets to the view.
If your using Spring MVC and @RequestMapping
, a really good place for this in your controller would be your @ModelAttribute
method. For example:
@ModelAttribute("modelYouArePassingToView")
public ModelYouArePassingToView createDefault() {
//construct it with default values for "Content"
//attribute, and it will show up in textarea after the bindind
ModelYouArePassingToView myapv = new ModelYouArePassingToView();
myapv.setContent(..); //default value
return myapv;
}
In your form, make sure to include the modelAttribute
tag attribute:
<form:form modelAttribute="modelYouArePassingToView" ...>
<form:textarea path="content" ..>
I faced a similar situation. The below code:
<form:textarea path="Content" id="my-text-box">${content}</form:textarea>
Worked out for me.
This works in Spring 4 where the form:textarea tag must be empty:
<form:textarea path="content" value="${Object.content}"/>
You have to use JS along with Spring MVC to make this work. This is what I did:
Change your textarea to basic html as below:
<textarea id="myTextArea" onchange="here();">${content}</textarea>
OR
<textarea id="myTextArea" onchange="here();">third hello world!</textarea>
Add a hidden input field, using spring mvc:
<form:input type="hidden" id="content" path="Content" value="third hello world!"/>
Add the following JavaScript:
<script>
var text1 = document.getElementById('myTextArea').value;
function here() {
text1 = document.getElementById('myTextArea').value;
document.getElementById("content").value = text1;
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With