How to pass Variable from External JavaScript to HTML Form

拈花ヽ惹草 提交于 2019-12-03 00:49:59

问题


I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.

Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.

I need this value passed to the HTML page in a form field.

Javascript:

var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };

document.getElementById('adcode').value = divElement(); 

Afterwards it should be passed to this Form field

HTML Form Field:

<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>

  <br>
  </p>

Thanks for any help!


回答1:


Your HTML file needs to reference the JavaScript js file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.

JS file:

<script>
  var divElement = function(){
  divCode = document.getElementById(div1).innerHTML;
  return divCode; };

  document.getElementById('adcode').value = divElement(); 

  function GetDivElement() {
    return divElement();
  }
</script>

HTML file:

<p>Ad Code:
  <br />
  <input type="text" name="adcode" id="adcode"/>
  <br />
</p>

<script src="wherever that js file is" />
<script>
  window.onload = function() {
      document.getElementById('adcode').value = GetDivElement();
  }
</script>

Although, really, this might do what you want (depending on what you are trying to do):

<p>Ad Code:
  <br />
  <input type="text" name="adcode" id="adcode"/>
  <br />
</p>

<script src="wherever that js file is" />
<script>
  window.onload = function() {
      GetDivElement();
  }
</script>



回答2:


Can it be this?:

function divElement(divCode){
return divCode; 
}

divElement(document.getElementById('adcode').value); 


来源:https://stackoverflow.com/questions/19644906/how-to-pass-variable-from-external-javascript-to-html-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!