I have written the following code to display an input with Javascript's alert( ... ) function.
My aim is to take a URL as input and open it in a new window. I concatenate it with 'http://' and then execute window.open().
However, I just get 'http://' in the URL name, even after concatenation, and not the complete URL. How can I fix this?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body onload="onload();">
<input type="text" name="enter" value="" id="url_id">
<input type="button" value="Submit" onclick="func();">
</body>
<script type="text/javascript">
var url;
function onload() {
url = document.getElementById("url_id").value;
}
function func(){
var var1 = "http://";
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
</script>
</head>
</html>
You shouldn't be calling it in onload(), only after the user has entered the url into the input field. Of course its an empty string, because you assign url to the value of #url_id before the user has a chance to enter anything when you place it in onload().
function func(){
var var1 = "http://";
url = document.getElementById("url_id").value;
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
Others have given solutions, and you already have accepted one. But none of them have told you what is wrong with your code.
Fristly, you have a body element inside your head element. This is invalid markup. Please correct it:
<html>
<head>
<!-- this is a script -->
<script type="text/javascript">
// javascript code
</script>
</head>
<body>
<!-- this is an inline script -->
<script type="text/javascript">
// javascript code
</script>
</body>
</html>
Secondly, you need to have an idea about the execution order of JavaScript inside browser windows. Consider this example:
<html>
<body onload="alert('onload')">
<p>Lorem Ipsum</p>
<script type="text/javascript" >
alert('inline');
</script>
</body>
</html>
Which alert do you thing will get executed first? See the JSFiddle.
So as you can see, inline JavaScript will be executed first, and then the browser will call whatever code is in <body onload=.
Also, onload function is called immediately after the page is loaded. And user has not entered anything when the function is executed. That is why you get null for url.
function func()
var url = document.getElementById("url_id").value;
var fullUrl = "http://".concat(url);
alert(fullUrl);
// or window.open(fullUrl);
}
You're not concatenating with a String but with an Object. Specifically an HTMLInputElement object.
If you want the url from the text input, you need to concatenate with url.value.
if its not concatenating, use:
var res = val1+val2.value;
Related
I have tried to call the function using window.onload but it works only when I place it body tag as below but when I place it in the head tag (commented out) it doesn't work though the function gets called (I have put an alert and checked.)
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
//window.onload = onl();
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<script>
window.onload = onl();
</script>
<div id = "txt">
</div>
</body>
</html>
It doesn't run in the head because the brackets used after the assignment cause the function to immediately be run. That mean it causes an error because the document hasn't loaded yet and so causes the form elements to be undefined.
In the head, if you change
window.onload = onl();
to
window.onload = onl;
Then it will work.
You must pass the handler function to document.load (or window.load), not the return of your function. So use document.onload = onl; instead of document.onload = onl(); (see more here : https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)
So in result :
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
document.onload = onl;
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<div id = "txt">
</div>
</body>
</html>
Regards,
Julien Q.
Edit : Sorry I misread before ;)
When you assign a function like that, you need to be sure not to invoke it. When you put parentheses on the end of a function name, it will be invoked immediately even if it's being assigned to something like the window's load event.
So, you simply have to replace onl() with onl:
window.onload = onl;
As for why it works in the body, it's because the document has pretty much finished loading when it gets to the end of the body.
Assigning onl() to the window's onload property isn't erroneous because you're assigning the return value of onl(), which is undefined, to window.onload.
Also, I'd recommend not using window.onload but document.onload, because document.onload is fired when the DOM is ready, not when the files requested are ready.
I am trying to generate QR code on my webpage with a data (id) I get from web service. I can not figure out how to insert a javascript variable as a part of <img> src parameter.
As you can see I can change the src using myFunction (AFTER button clicked). But I do not know how to insert id variable to the initial page load (to replace ID1_GOES_HERE at the end of img line).
Please help!
Here is a code:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id2;
}
</script>
<img id="qr_img" src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl=ID1_GOES_HERE"/>
<button onclick="myFunction()">test</button>
</body>
</html>
Don't use a button click handler, just call the function from your script:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = document.getElementById('qr_img').src + id2;
}
myFunction();
</script>
<img id="qr_img" src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="/>
<button>test</button>
</body>
</html>
The click handler is used to capture the button click event, and do something at that time. That's not what you want, so remove the button click handler.
At the end of the <script> element, simply call myFunction() to do what it's intended for.
If you wanted to run the script after the entire document and all of its dependencies were loaded, you could do this:
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = document.getElementById('qr_img').src + id2;
}
document.onload = myFunction();
</script>
For this simple case, you probably don't actually need a function at all, and the body of myFunction can simply be placed inline, like so:
<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = document.getElementById('qr_img').src + id2;
</script>
The function would be useful if you had more logic involved, and needed to organize (or modularize) it.
You could add this to your script below where you declared and set the id1 variable
function Window_OnLoad ()
{
document.getElementById("qr_img").src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id1;
}
I'm struggling to implement this case, I really appreciate your help.
UPDATE :
page1.html
<html>
<head>
<title></title>
</head>
<body >
<form>
filled value : <input type="text" id="one">
</form>
</body>
</html>
page2.html
<form>
<input type="button" onclick='go();' value='call_page1'/>
</form>
First attempt : page1 shows up, but value is not set
<script>
function go(){
var newWindow;
newWindow= window.open('page1.html', 'form', 'width=400,height=350');
newWindow.document.getElemetById('one').value='xxx';
}
</script>
Second attempt : page1 is not even shown up
<script>
function go(){
var detailsWindow;
detailsWindow = window.open('page1.html', 'form', 'width=400,height=350');
detailsWindow.onload = function{
document.getElementById('one').value='test';
}
}
<script>
Question : setting value' value to page1.html, when it's called in page2.html?
Or if there's an alternative (but please take it easy on me, i'm just learning this stuff ). I don't use JQuery, if there's something unclear, i'm happy to hear it.
regard.
// page1.html
<script>
var newWindow = window.open('page2.html', 'formUntukUpdate', 'width=400,height=350');
newWindow.onload = function(){
newWindow.document.getElementById('one').value = 'ok 2';
};
</script>
// page2.html
<input type="text" id="one" value="ok" />
First of all javascript is case sensetive, and n is missing. so replace getElemetByID with getElementById.
Second is that the code executes immediately and doesn't wait the page to load. You must wrap your code in window.onload :
newWindow.onload = function(){
newWindow.document.getElementById('one').value='xxx';
}
there's 3 bugs in the update:
function in detailsWindow.onload = function must be declared with detailsWindow.onload = function() to work.
your end script is must be replaced from <script> to </script>
you are missing detailsWindow in document.getElementById('one').value = 'test'; it must be detailsWindow.document.getElementById('one').value = 'test';
I Have edited the code, the updated code is below, This code is not able to fetch the keywords meta tag, hence it is not working.
old description: I am trying to concatinate the strings to get the finalUrl, but I am not able to do so becuase of the tags variable. I need to fetch the keywords meta tag of the page and append it to get the finalUrl. Any help?
<script type="text/javascript">
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/details/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
function loadJSON(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
}
function showGameDetail(feed){
var title = feed.title;
var game_url = feed.pscomurl;
var packart_url = feed.Packart;
$("#bnr-ads-box").html("<img src='"+"http://abc.com/"+packart_url+"'>");
}
loadJSON(finalUrl);
</script>
<div id="bnr-ads-box"></div>
<!DOCTYPE html>
<html>
<head>
<meta id="metaK" name="keywords" content="customizable software for QuickBooks, QuickBooks-integrated, Method customization, CRM accounting, Method for QuickBooks, Method CRM, Method blog, Salesforce automation, Method online platform, QuickBooks customization, web-based platform, industry-specific, customer portal, Method Field Services, Method Manufacturing, ERP" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
document.getElementById("demo").innerHTML=finalUrl;
}
</script>
</body>
</html>
change this
var tags="$('meta[name=keywords]').attr("content");";
to
var tags=$('meta[name=keywords]').attr("content");
also use this code var finalUrl = gameurl + tags + jsn;
What you need is to escape the double quotes inside your tags variable, like so:
var tags="$('meta[name=keywords]').attr(\"content\");";
Cris' solution is also fine, but in some case you will need to have two sets of double quotes inside a string so you will be forced to do escaping correctly.
FYI: Escaping is the process of having special characters getting generated in a string which would otherwise cause issues, for instance in javascript you can't have newlines in a string, like this:
var mystring = 'on
a different line'; // <- this causes a syntax error
So one would do the following:
var mystring = 'on\na different line';
You forgot to include the jquery
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="hello"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
alert(finalUrl);
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Tough debatable, you can use an array, which can be concatenated by calling join():
var tags = $('meta[name=keywords]').attr("content");
var data = [
"http://xyz/abc/names/",
encodeURIComponent(tags),
".json?callback=showGameDetail"
].join('');
$("#demo").html(data);
Actually the concat method works on strings too (in chrome at least) but the recommended method is using the plus concatenation string operator
You are however missing some stuff
jQuery library - I assume you want that since you have $(...) in the example
encoding of the string from the keywords - I use encodeURIComponent to handle possible newlines and quotes in the keywords
.
<!DOCTYPE html>
<html>
<head>
<title>Create a URL from keywords</title>
<meta name="keywords" content="These are tags" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function myFunction() {
var tags = $('meta[name=keywords]').attr("content");
var URL ="http://xyz/abc/names/" +
encodeURIComponent(tags) +
".json?callback=showGameDetail";
window.console && console.log(URL);
$("#demo").html(URL);
}
</script>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
I have a number of links, that when clicked on, passes a variable thru to another portion of the page.
Yet, for some reason, I can’t figure it out! What am I missing?
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
return myid;
}
</script>
</head>
<body>
Click Me<br />
<script type="text/javascript">
document.write(myid);
</script>
</body>
You are getting a little mixed up here. Even though the function returns a value, it has nothing to return it to. Try this:
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
document.getElementById("debug").innerHTML = myid;
}
</script>
</head>
<body>
Click Me<br />
<div id="debug"></div>
</body>
if you want to use it later you need to declare myid as a global variable. its scope is currently only within myFunction. also the document.write() function will only execute at runtime so you need to have another function the executes that with every click, or just combine the two.
When you click the link all that happens is that the myFunction() is called which returns the string. The line document.write(myid); is not executed anymore so nothing is visible.
<script>
// This is global
var myid = ''
myfunc = function(a){
myid = "Hi There!" + a;
alert(myid);
}
test_global = function(){
alert(myid);
}
</script>
Set MYID
<input type="button" onclick="test_global();" value="Test MYID" />
Here is a simple example of some similar stuff:
clickme or ClickMeAlso
<input id='other' type='text'/>
<script>
function myfunc(a) {
return a + " howdy";
};
</script>
You can see this in action here:http://jsfiddle.net/5Sbn2/