Forum Stats

  • 3,814,867 Users
  • 2,258,922 Discussions
  • 7,892,882 Comments

Discussions

AppendChild problem

920164
920164 Member Posts: 47
edited Mar 8, 2012 5:34PM in Java Programming
Hi all
I am adding the following script at the end of my JSP to add a hidden field but it dosent work unless i add an alert statment before appending the new element, dose anyone have any explanation of this strange behavior?



<%
String transactionNo =request.getParameter("transactionNo");
System.out.println("PSS At error footer jsp -----" + transactionNo);
%>
<script language="JavaScript" type="text/javascript">
var inputFeild = document.createElement("input");
inputFeild.type = "hidden";
inputFeild.name = "transactionNo";
inputFeild.value = "<%=transactionNo%>";
var formsCollection = document.getElementsByTagName('form');
// i i add alert here, it works!!!!
for(var i=0;i<formsCollection.length;i++){
document.getElementsByTagName('form')[0].appendChild(inputFeild);
}
</script>

Answers

  • gimbal2
    gimbal2 Member Posts: 11,949 Gold Trophy
    edited Mar 8, 2012 9:29AM
    As a test, in stead of executing that javascript at the end of the page, put it in a function and invoke it in the onLoad() handler of the body tag. Does it then work correctly?

    Let me explain what my line of thinking is: you are attempting to modify the document before the page is fully loaded - that doesn't seem like a good idea to me. When you trigger this in onLoad(), you are guaranteed to be executing it when the full DOM tree has been created. At the very least, it is a good test.


    BTW: there is a JSP forum. Please take the time to pick the proper sub forum for a question.
  • 920164
    920164 Member Posts: 47
    Thanks for your reply, i can understand you very well and what you suggested is working very well, but my problem is that i have more than 50 jsps that are already written, and i dont want to touch all o them, instead i searched for a jsp that is included in all o them footer.jsp and added the required script their. do you have any better approach?
  • 917161 wrote:
    Thanks for your reply, i can understand you very well and what you suggested is working very well, but my problem is that i have more than 50 jsps that are already written, and i dont want to touch all o them, instead i searched for a jsp that is included in all o them footer.jsp and added the required script their. do you have any better approach?
    I would use jquery's document ready function. You can add that in your footer.jsp. Something like
    $(document).ready(function(){
       // Your code here
    });
  • EJP
    EJP Member Posts: 32,920 Gold Crown
    edited Mar 8, 2012 5:34PM
    Crosspost, and JavaScript question in Java forum on Java site. Off topic. Locking.
This discussion has been closed.