Most of the solutions I have found deal with localized javascript instead of an external file so I am posting this question.
Links to attempted solutions:
Turn HTML Form Input into JavaScript Variable
I want to take a html form input and use that input in an external javascript file.
The html form input comes from index.html
<script src="script/our.js"></script>
<div class="searchbar">
<form action="">
<input type="text" placeholder="search ..." name="query" onchange=formChange()>
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
var searchThis = document.getElementsByName("query").value;
}
</script>
Then, our.js tries to use the variable like so:
var Manager;
(function ($) {
$(function () {
Manager.store.addByValue('q', searchThis);
});
})(jQuery);
With my current setup, if I searched a term ("unlock") the form will send and the page will show it has found 0 documents. It does not say that searchThis is undefined
The back end of my js works with searchThis being replaced by "*:*" to display all records instead of those with the searched string.
EDIT #1 : Manager.jquery.js to see if I need to allow for search term to be a variable an not just a string
REDACTED
EDIT #2 :
I have been trying suggestions below. Currently:
index.htmlchanged
<script>
function formChange(){
var searchThis = document.getElementsByName("query")[0].value;
console.log(searchThis);
window.searchThis = searchThis;
console.log(window.searchThis);
}
</script>
our.jschanged
Manager.store.addByValue('q', window.searchThis);
The console.logs in index.html return my search term. However if I do the same just before window.searchThis is called in our.js it returns as undefined.
EDIT #3
I have been playing with importing the searchThis variable. I cannot import window.searchThis because I get an error for unexpected . In full when I try:
import searchThis from "../index.html"
It gives me an error stating:
Failed to load module script: The server responded with a
non-JavaScript MIME type of "text/html". Strict MIME type checking is
enforced for module scripts per HTML spec.
EDIT #4 : my <form> + <script> section with adjustments
<div class="searchbar">
<form>
<input type="text" placeholder="search Nicola..." name="query" onsubmit=formChange() >
<button type="submit">sendit bro</button>
</form>
</div>
<script>
function formChange(){
searchThis = document.getElementsByName("query")[0].value;
term = searchThis;
console.log(term);
}
</script>
<script defer="defer" src="script/our.js" type="module"></script>
Ive added my form section because I could be doing something wrong here too. When I go to my main page the console.log on our.js has already been logged as undefined. When I enter a search term with onchange instead of onsubmit the console logs from my <script>. Once I hit submit, the page flashes and the log for our.js is again at the top and undefined.
EDIT #5 : pic of logs described above (before submit)
You could use the window object.
Add a new property named searchThis to the window object and assign the obtained value of the searchThis variable.
function formChange() {
var searchThis = document.getElementsByName("query")[0].value;
window.searchThis = searchThis;
}
Then, just call it by using window.searchThis:
var Manager;
(function($) {
$(function() {
Manager.store.addByValue('q', window.searchThis);
});
})(jQuery);
Update: document.getElementsByName("query") returns a NodeList. You could use document.getElementsByName("query")[0] to refer to a single element.
The availability of a variable for reuse in another external file depends on the order of loading or initialization.
The issue that you have is that our.js is running before the window.searchThis is declared.
You can do:
Add a defer attribute in the script tag. Example: <script defer="defer" src="script/our.js"></script>.
OR
Put the <script src="script/our.js"></script> at the end.
Something like this:
<script>
function formChange() {
var searchThis = document.getElementsByName("query")[0].value;
window.searchThis = searchThis;
}
</script>
<script src="script/our.js"></script>
Related
I have an HTML file with a basic form. I am calling a function on button click, but on click I receive "function is not defined". Everything appears to be in order vis-a-vis pointing to files, so I'm not sure where the disconnect is.
This is the layout:
and these are my index.html and main.js, respectively:
<!--index.html-->
<form action="" method="get" class="form">
<label for="form-input">Paste Key Here: </label>
<input type="text" name="Key Input" id="form-input">
<button id="form-button" type="button" onclick="GWAPIUser()">Click Here!</button>
<script type="application/javascript;charset=utf-8" src="/public/javascripts/main.js"></script>
</form>
/* main.js */
const key = 'authkey';
async function GWAPIUser() {
const response = await fetch(`https://api.guildwars2.com/v2/account/achievements?access_token=${key}`);
const data = await response.json();
console.log(data);
};
Directory was made with express-generator. This is my first time using it, so I'm not sure if that means anything.
Finally, this is the error I receive:
Uncaught ReferenceError: GWAPIUser is not defined at HTMLButtonElement.onclick (?Key+Input=:18)
Browsers do not like application/javascript;charset=utf-8 as a value for the type attribute.
"Non-modular JavaScript" is the default type for a script so you should omit the type attribute entirely in this case. Only include it if you need to specify type="module" or as a hack to store data in an element without rendering it.
<script src="/public/javascripts/main.js"></script>
Hmm is it possible to document.write on other html page?
For example I create a two html page, the first page have a textfield and submit button. I enter a text in a textfield and after I click the submit button the value of the textfield will be transfer to the second html page and load the html page and write the value on it.
Just a beginner to javascript so bear with me please :D
You can do this by using Query String.
window.location = "Pass.aspx?variabletopass=test";
Use this line of where you are trying to redirect your page,and value of your textfield in query string.
Since you're using pure javascript and HTML, I assume server-side things are out of the picture. So Felix Kling's comment is actually, I think, a good way to go. Here's one way you could use localStorage to make this work:
/* index.html */
<form action="result.html" onsubmit="submit()">
<input type="text" id="input">
<input type="submit" value="Submit">
</form>
<script>
function submit() {
var input = document.getElementById("input").value;
localStorage.input = input;
}
</script>
/* result.html */
<div id="result"></div>
<script>
document.getElementById("result").innerHTML = localStorage.input;
</script>
Without using php you can document.write() submitted text on other html file as follows.
<html>
<script>
var a = document.location.toString();
var b = a.slice(a.indexOf("?")+1,a.length);
var c = b.split("&");
for(i=0;i<c.length;i++){
document.write(c[i]);
}
</script>
</html>
If you are working on Single page Application you can quite easily achieve this, by just storing the value in correct scope.
If you are on multiple page application you can achieve this by any of the following ways:
sending parameter in url
storing value in localStorage/sessionStorage
storing it in cookie(Not recommended)
sending it to server in forms param(Not recommended)
I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/
I have an .aspx page. I populate a public variable in the code behind (.cs) page and then access that variable in JS on client side. I have the script declared after the FORM tag as below :-
<body>
<form>
...
</form>
<script language="javascript" type="text/javascript">
debugger;
var data = "<%=cSharpData%>";
</script>
</body>
After postback this script does not get executed first time, but when I click on any other server button on the page, then it gets executed.
Any idea why?
Is your postback done with ajax?
If so then only part of the page is refreshed and the script is not executed again.
You can wrap it in a function and add that function to the postback callback handler.
This is how I did it on one site:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { edit.update(); });
Putting some Javascript after a <FORM> element does not mean it will get processed after the form has been submitted. It gets processed as the HTML is rendered, which is what you are seeing.
If you want to run some Javascript after POSTing a form then you need to use a onClick handler, something like this:
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="dosomejavascriptstuff()">
</FORM>
have you tried to execute it with jquery $(document).ready()?
something like:
<script language="javascript" type="text/javascript">
$(document).ready(function(){....});
</scrip>
updated
without jquery
/* registr event on document load */
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", log4link, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
if ( document.readyState === "complete" ) {log4link();}
});}
Thanks for your replies. I got closer to the issue but I do not know the solution :(
The C# variable contains a path info as "D:\" and when I set this on a JS variable I get the error as "Unterminated String Constant".
How do I overcome this.
Actually this was the problem, why the script was not getting executed. As soon as I removed the "\", it worked !
I'm developing the ajax search script.
it's the simple code, I get javascript error. I can't see the error!
And I don't understand why I have an error here:
<script>
var keywords = document.advanced_search.keywords.value;
alert(keywords);
</script>
<form name="advanced_search">
<input name="keywords" type="text" value="213123">
</form>
JavaScript error : 'document.advanced_search.keywords', null or not the object.
Try to move script block after the form. Your script is run in time when form doesnt have to exist yet.
In order to access DOM elements from JavaScript you should use document.getElementById("keywords").
<script>
var keywords = document.getElementById("keywords");
alert(keywords);
</script>
<form name="advanced_search">
<input id="keywords" name="keywords" type="text" value="213123">
</form>
And this have to be called of course after the DOM is loaded.
So:
<script>
window.onload = function(){
var keywords = document.getElementById("keywords");
alert(keywords);
}
</script>