简体   繁体   中英

How to pass a variable from a html form to a .js file?

Here is my code

File external.js:

var TRange=null;

function findString (str) {
 if (parseInt(navigator.appVersion)<4) return;
 var strFound;
 if (window.find) {

  // CODE FOR BROWSERS THAT SUPPORT window.find

  strFound=self.find(str);
  if (!strFound) {
   strFound=self.find(str,0,1);
   while (self.find(str,0,1)) continue;
  }
 }
 else if (navigator.appName.indexOf("Microsoft")!=-1) {

  // EXPLORER-SPECIFIC CODE

  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
 }
 else if (navigator.appName=="Opera") {
  alert ("Opera browsers not supported, sorry...")
  return;
 }
 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}

File Search.html:

<html>
<head></head>
<title>Search</title>
<body>
<form name="input" action = "external.js">
Search for: <input type="text" name="keytext" /><br />
</form>
<p> You can search this text. Search the text again</p>
</body>
</html>

I am looking for a method to modify the form part of the HTML file such that it can make a call to the external JavaScript (external.js) and pass the parameters. The parameter will be the text in the input box.

in your search.html add a reference to the javascript file. like so

<script src="external.js" type="text/javascript"></script>

you can then call functions within the javascript file like so

<input type="text" name="keytext" onClick='findString("test")'/>

in this example you'd be passing the string "test" to your function findString

Edit: you can use other events like onblur as well, it all depends when you want to fire the event.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM