开发者

getting hidden fields value

I am working on a Struts2 application. I am setting the value of a hidden field in JSP with the purpose to access it by JavaScript.

My JSP code:

<s:iterator value="collegelist">
    <tr>
        <td align="center"><s:property value="collegename"/></td>
        <s:hidden name="hiddenname" key="collegename" />  
    </tr> 
</s:iterator>

My JS code:

var myForm = document.frmAction;
var开发者_如何学JAVA text = myForm.hiddenname.value;
alert("hidden field text is:" + text);

The alerts shows a blank value.

What is the cause and how can I solve this?


Try

element = document.getElementsByName("hiddenname");
alert(element[0].value);


You generate multiple fields having the same name, since your code is inside a s:iterator tag. You should obviously have such a loop in your Javascript as well :

var hiddenFields = document.getElementsByName("hiddenname");
for (var i = 0; i < hiddenFields.length; i++) {
    alert("hidden field text is::" + hiddenFields[i].value);
}

Also, verify the the value is not blank in the generated HTML, and that the hidden fields'a name is hiddenname.


I tried your code and it surely works.. problem is somewhere in your server code itself..

Look here: http://jsbin.com/ajajo4/2/edit


Make sure you have only one form with the name "frmAction" and only one hidden field with the name "hiddenname". If you have multiple, you'll get an array instead of a single value.


The root of the problem is that you are inside of an iterator. Struts updates the name for you in order to correctly hook everything up. If you pull up your page and view source, your hidden field will probably look something like this:

<input type="hidden" name="collegelist[0].hiddenname" value="thename"/>

Regardless, if you want the retrieval by name to work, do not trust the name that you supply to a struts tag. Always pull up the generated source and look at what name the field actually has.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜