Concatenate Strings in JavaScript - javascript

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>

Related

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.
What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).
HTML:
<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script>
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>
</head>
<body>
<form >
player one name: <input type="text" id="firstname"><br>
player two name: <input type="text" id="secondname"><br>
<input type="submit" onclick="checkNames();"/>
</form>
</body>
</html>
JavaScript:
function checkNames(){
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
//window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
//window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}
I have commented the two other options I tried which also do not work.
You are using an HTML form... this means that your submit button will fire and try to submit your form.
In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.
function checkNames() {
event.preventDefault();
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
window.location.href = 'SOME-PATH/Game.html';
}
To redirect to a page in your computer you can use:
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';
There are more than one way of passing the values to another page. Here is an example using query string.
In the page that has the values.
var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;
In the page receiving the values.
var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];
Use
window.location="url";

How do I use this JavaScript variable in HTML?

I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
This is my code so far:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
</body>
I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() {
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>
You can create a <p> element:
<!DOCTYPE html>
<html>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
p = document.createElement("p");
p.innerHTML = "Your name is "+lengthOfName+" characters long.";
document.body.appendChild(p);
</script>
<body>
</body>
</html>
You can create an element with an id and then assign that length value to that element.
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('message').innerHTML = lengthOfName;
<p id='message'></p>
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
Try this:
<body>
<div id="divMsg"></div>
</body>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.
The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.
There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).
Examples for both options:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
<p id="a"></p>
<p id="b"></p>
<script>
document.getElementById('a').innerHTML = name;
document.querySelector('#b').innerHTML = name.length;</script>
</body>
You could get away with something as short as this:
<script>
const name = prompt("What's your name?") ?? "";
document.write(`<p>${name.length}</p>`);
</script>
It's not a very clean way of doing it but using document.write is not much worse than calling prompt() as soon as the page loads.
A more user-friendly approach would be to have an actual text input on the page and to dynamically update the length as they type using an event listener.
<label>Name: <input id="name-input"></label><br>
Length: <output id="name-length-output" for="name-input">0<output>
<script type="module">
const nameInput = document.getElementById("name-input");
const nameLengthOutput = document.getElementById("name-length-output");
nameInput.addEventListener("input", e => {
nameLengthOutput.textContent = nameInput.value.length;
});
</script>
If you want to learn how to manipulate pages with JavaScript, the Mozilla Developer Network has a good tutorial about the DOM.

Issue with getElementById

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;

how to display only first 10 characters of file name that they upload in the html page

The code to print the file name is
<div id="file">'+filename+'</div>
i want only the first 10 characters of the file name and not the all. what java script function can i use as i cannot use php.
Not sure if you wanted the code for getting the DIV contents as well.
Complete example below:
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="file">I want the first 10 characters</div>
<script>
$(document).ready(function() {
var div = $('#file');
var str = div.text();
var stripped = str .substr(0, 10);
alert(stripped);
});
</script>
</body>
</html>
var str = "this is isdfisdf";
console.log(str.substr(0, 10));
To get the first 10 characters from a string in JavaScript use substr()
var str = str.substr(0,10);
or using substr() in PHP :
$str = substr(str,0,10);

Why doesn't JSON.parse work?

Why doesn't JSON.parse behave as expected?
In this example, the alert doesn't fire:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing JSON.parse</title>
<script type="text/javascript" src="js/json2.js">
// json2.js can be found here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
</script>
<script type="text/javascript">
function testJSONParse()
{
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));
}
window.onload = testJSONParse;
</script>
</head>
<body>
</body>
</html>
In firefox, the Error Console says "JSON.parse". Not very descriptive..
This is a simplification of a problem I have which uses AJAX to fetch data from a database and acquires the result as a JSON string (a string representing a JSON object) of the same form as text in the example above.
Your JSON is not formatted correctly:
var text = '[{"a":"w","b","x"},{"a":"y","b":"z"}]';
^-- This should be a ':'
It should be:
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
error in typing
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
//below is correct one
var text = '[{"a":"w","b":"x"},{"a":"y","b":"z"}]';
alert(JSON.parse(text));

Categories

Resources