I keep getting an error saying my function "key" is not defined. Here is the HTML code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
<script language="text/javascript" src="main.js"></script>
</head>
<body onkeypress="key()">
<p>Money: <p id="money">0</p></p>
</body>
</html>
And the JavaScript:
int money = 0;
function key()
{
money += 1;
document.getElementById("money").innerHTML = money;
}
var money = 0;
instead of
int money = 0;
First: text/javascript is not a language supported by the browser's scripting engine, so the browser will ignore the script.
If you were writing HTML 3.2 you would say:
language="javascript"
If you were writing HTML 4 you would say:
type="text/javascript"
It is 2014, so write HTML 5 and don't specify a type or language attribute at all.
Second, int money = 0; is invalid JavaScript. (You seem to be trying to write Java.). So the script will throw an exception and stop at that point.
Use var to declare variables (of any type) in JS.
var money = 0;
Related
So, I'm trying to build a decimal to binary converter for my computer science class. I already made an algorithm in Python that seems to be working pretty well. It works in the Javascript console perfectly fine too. I'm now at a point trying to accept input from an HTML form. I'm kind of a DOM noob, but I thought this would be something easy and fun to do, but it's turning out that it's a lot more confusing than I thought. I would know how to do this in React.js, but I'm trying to use this as a learning experience. Basically, I want to take input from a form, run it through a function and have the returned value of the function back into HTML. I know how to get the value into HTML, but I have no clue how to retrieve the form data into Javascript. Here's a Codepen with my progress so far.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Binary Calculator</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<center><form style="margin-top: 25%" id="myForm">
<input type="text" class="form-control" style="width: 250px" placeholder="Type a number!" id="textForm">
<br />
<input type="button" class="btn" style="margin-top: 15px" value="Submit">
</form></center>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function conversion(){
var quotient = 15;
var convertedNum = [];
if (formValue == 0){
convertedNum = [0]
}
while(formValue >= 1){
quotient = formValue/2;
var mod = formValue %2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
console.log(convertedNum.join(""));
}
$('#textForm').change(function(){
var formValue = document.getElementById('#textForm').value;
parseInt(formValue);
console.log(formValue);
console.log("It's Working in Console!");
conversion();
});
Her's a simple way doing what you are trying to accomplish.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<body>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You want to put the answer back onto the page to be displayed when they click submit?
First you'll need a container (well, you can create one on the fly in Javascript, but typically you would just create an empty div container to hold the answer).
Add a div container for the solution: (after form probably)
<div id="convertedToBinary" class="answerDiv"></div>
It looks like you're using jQuery, which makes entering HTML into a target easy.
Add this to your conversion function:
$('#convertedToBinary').html(formValue+" converted to binary is: "+convertedNum.join("") );
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="form-control" />
<span id="result"></span>
<script>
var formValue;
function conversion()
{
var quotient = 15;
var convertedNum = [];
if (formValue == 0)
{
convertedNum = [0]
}
while (formValue >= 1)
{
quotient = parseInt(formValue / 2);
var mod = formValue % 2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
$('#result').html(convertedNum.join(""));
}
$('.form-control').keydown(function ()
{
var $this = $(this);
setTimeout(function ()
{
formValue = $this.val();
conversion();
}, 100);
});
</script>
</body>
</html>
Just a couple of hints starting from the HTML / JS you provided:
You are using a jQuery selector within plain JS, so this won't work:
var formValue = document.getElementById('#textForm').value;
Change that to
var formValue = document.getElementById('textForm').value;
if you want to use plain JavaScript - or do it the jQuery way, like so
var formValue = $('#textForm').value;
You could also have stored the reference to that DOM element in a var, up front, and then work on that, but that's another topic.
Also you must pass the formValue to the conversion function, like so
conversion(formValue);
otherwise you can't work with the input value within the function scope.
All that remains to do is writing the resulting value into the innerHTML of some . The other answers give you two options for doing that - in jQuery (innerHTML) or plain old JavaScript.
I'm new to JavaScript and already encountered a problem. When I run the code and the browser pops up, it[browser] does not show anything. What I have is the testMethod.js file with one method:
function testMethod(num1, num2){
var value = num1 + num2;
return value;
}
and an HTML file from where I'm trying to run:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> My JavaScript</title>
<script language = "javascript" src = testMethod.js"></script>
</head>
<body>
<script language = "javascript" type = "text/javascript">
// var getValue = testMethod(2,3);
document.write("The result is " + testMethod(5,3));
</script>
<noscript>
<h3> This site requires JavaScript</h3>
</noscript>
</body>
</html>
The code is not implementing the result at all. It shows only a blank page browser.
It seems you have a quote missing in the html, it should say src="testMethod.js" where you are including the script in the first place.
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 been using javascript for the last couple of days and have decided to use it for my website. I also decided to use external functions in a single .js file
function imageLoad() {
var path,domain,cut;
path = window.location.pathname;
domain = "WEBSITE DOMAIN ADDRESS";
cut = path.substring(domain.length,path.length);
/* Still in progress */
}
function pageStart() {
var image-on = 0;
var imgArray = new Array();
alert("boo"); /* Used to check the script will run */
}
Now that's a simple process. Nothing too complex. And I have done the following (it is a code extract of my template)
<script type="text/javascript" src="main_script.js"></script>
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>Grandpa Pixel</title>
</head>
<body onload="pageStart();">
Now that should do the trick. On body loading, it should cause an alert "boo". But it doesn't. It just loads the page normally. However If I make the external script ONLY contain the line alert("boo"), it works perfectly. Can I ask why this is the case? Does this mean you can only have one function per external file?
check this:
function pageStart() {
var image_on = 0;
var imgArray = new Array();
alert("boo"); /* Used to check the script will run */
}
HTML
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>Grandpa Pixel</title>
<script type="text/javascript" src="main_script.js"></script>
</head>
<body onload="pageStart();">
recommended using Firebug or other debuggers.
ERRORS
SyntaxError: missing ; before statement
var image-on = 0;
main_script.js (line 12, col 13)
ReferenceError: pageStart is not defined
pageStart();
SOLUTION
change
var image-on = 0;
with
var imageOn = 0;
it would be cleaner to put the <script> tag into the <header> tag.
I'm using HTML publisher in hope to have a html page with some javascript codes running on hudson. The HTML code is like this:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../stringformat.js"></script>
<script type="text/javascript">
......
sql=String.format("/.csv? select from table where exchange=`ABC......")
</script>
</head>
However, after a successful build, my html page doesn't show what it suppose to, and as I check the error console, it says
Error: TypeError: String.format is not a function
I have put my stringformat.js into the top folder, as the HTML publisher doesn't seem to allow the file to contain anything other than HTML files.
Can anyone tell me why the String.format is not loaded properly? Thanks!
PS: stringformat.js is the file i got from
http://www.masterdata.se/r/string_format_for_javascript/
The code should be working properly as this piece of code works outside the hudson
try code:
<html>
<head>
<title>String format javascript</title>
<script type="text/javascript">
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var _myString = String.format("hi {0}, i'am {1}","everybody", "stackoverflower");
function show(){
alert(_myString);
}
</script>
</head>
<body>
<input type="button" name="btnTest" id="btnTest" value="Test string format" onclick="show();" />
</body>
</html>