0

The input field is not printing the value generated from the function domainRef.

Here is my code :

<div id="divref" onpageshow="domainRef()">

<script>
function domainRef(){
var ref = document.referrer.toString();
 document.getElementById("test").value = ref ;
}                          
</script>
</div> 

<input type="hidden" id="test" value="">

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
B4b4j1
  • 384
  • 1
  • 4
  • 15
  • 2
    Probably executing before the DOM has finished rendering. Try using something like [this](https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery) – Lewis Apr 05 '19 at 10:23

2 Answers2

1

The following works for me:

<div id="divref">
  <script>
    window.onload = domainRef;

    function domainRef() {
      var ref = document.referrer.toString();
      document.getElementById("test").value = ref;
    }
  </script>
</div>
<input type="hidden" id="test" value="">

The problem is that most likely the DOM has not been fully loaded when theonpageshow event is triggered. A similar solution is to trigger the function using the onload event attribute on the body element.

<body onload=domainRef()>
  <div id="divref">
    <script>
      function domainRef() {
        var ref = document.referrer.toString();
        document.getElementById("test").value = ref;
      }
    </script>
  </div>
  <input type="hidden" id="test" value="">
</body>

For the latter solution I have created a jsFiddle where I have removed the hidden attribute to show the input field with the resulting value.

Marcus
  • 745
  • 6
  • 17
1

Try this one

<div id="divref"></div>
<input type="hidden" id="test" value="">
<script>
  domainRef();
  function domainRef(){
    var ref = document.referrer.toString();
    document.getElementById("test").value = ref ;
  }                          
</script>