I need some troubleshooting with my HTML/JavaScript code - javascript

I am trying to create code that when you press a button, it will change the value of a variable and replace some text.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="unitts">You have 0 unitts</p>
<script type="text/javascript">
var unitt = 0;
function unittIncrease() {
var unittPrev = unitt;
unitt++;
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
}
</script>
<button id="unittIncrease" onclick="unittIncrease();">Digitize Unitt</button>
</body>
</html>
When I press the button, nothing happens to the text.
I don't know why this does not work.
Please help me!
EDIT: I am only 11 years old,
please don't throw your wizard
code at me.
maybe you should remove your button system and add a while loop that
automatically add a unit but waits one second with a setInterval
function

I think you should write the js code like this
document.getElementById('unitts').innerHTML = "You have"....
Instead of:
document.getElementById(unitts).innerHTML.replace("...")

Your JavaScript should be (note the unitts wrapped in quotes and the full stop removed):
document.getElementById('unitts').innerHTML = "You have " + unitt + " unitts";
Instead of:
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
In the latter, it is looking for the non-existent variable unitts instead of the string 'unitts'. Also, you are looking for the text You have x unitts. which cannot be found because in your HTML, it is just You have x unitts without the full stop.
Edit
See this plnkr.

Apart from the issues that the other answer mentions, by calling .replace method on the .innerHTML property of the element, the content of it doesn't change. You should reset the property by using the returned value of the method call:
el.innerHTML = el.innerHTML.replace(...);
Also, as you are trying to increase a number, instead of replacing all the characters, you can just replace the numeric part:
var unitts = document.getElementById('unitts');
function unittIncrease() {
unitts.textContent = unitts.textContent.replace(/\d+/, function(n) {
return +n + 1;
});
}
https://jsfiddle.net/h6odbosg/

Related

jQuery append implementation is breaking

So I have this code that I am trying to alter –
Original:
jQuery(document).ready(function() {
var name = '';
var firstLastName = '[[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.first_name]]]] [[T6:[[E48:[[S334:fr-id]]-[[S334:px]]:cons.last_name]]]]';
var screenname = '[[T6:[[S48:0:screenname]]]]';
if (screenname) {
name = screenname;
} else {
name = firstLastName;
}
var splitName = name.split('');
var nameCheck = splitName[splitName.length-1];
jQuery('#personal_page_header h2').html("Support " + name + "'s Fundraiser" );
});
someone wrote this up and are no longer here, and what I'm trying to do now is figure out how to instead of replace the existing text, add to it.
So right now what this code does is it replaces the h2 content with the constituents registered name, or screenname.
What I'm trying to do now is append to that so that it will say something like
<h2>
Welcome to my fundraiser
<br/>
"Support" + name + "'s Fundraiser"
</h2>
but unfortunately what I tried breaks the code and stops it from working.
what I tried to do is this:
jQuery('#personal_page_header h2').append('<span><br />"Support " + name + "'s Fundraiser"</span>' );
I've tried to do a variety of other things that gave the same unsuccessful result.
Any help would be really appreciated!
Thanks
This should work for you:
jQuery('#personal_page_header h2').append("<span><br/>Support " + name + "'s Fundraiser</span>");
You've just got your quotations a little out of place.
You need to concatenate your code correctly, so if you'd like to keep the " use ' to concatenate. Further you need to escape the ' inside the string with \:
jQuery('#personal_page_header h2')
.append('<span><br />"Support ' + name + '\'s Fundraiser"</span>');

Enumerating properties and values using forEach

Below code does not enumerate the properties & values of Array constructor on a web page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
window.onload = myfunc;
function myfunc(){
window['Object']['getOwnPropertyNames'] (window['Array'])['forEach'](function(val){
document.write(val + ": " + Array[val] + "<br />" );
});
}
}
</script>
</head>
<body>
</body>
</html>
Is there any issue with the argument passed to forEach?
No the argument is fine, you have an extra } closing bracket.
window.onload = myfunc;
function myfunc(){
var x = "";
window['Object']['getOwnPropertyNames'] (window['Array'])['forEach'](function(val){
x += val + ": " + Array[val] + "<br />" ;
});
document.write(x);
}
I hope that you know document.write will replace the whole document. Moreover i have appended whatever you want to print in a variable x, you can use this x to display the output.
using Object.getOwnPropertyNames(Array); would be better
but if want to insist on you method then :
window['Object']['getOwnPropertyNames'] (window['Array'])['forEach'](function(val){
console.log(val);
});
you had an extra }
You have an extra closing curly brace in your code, which you can see easier when you fix the indentation of your code:
}
</script>
You can use window objects directly, there is no need for window['propertyName'].
window['Object']['getOwnPropertyNames'](...)
// is the same as
Object.getOwnPropertyNames(...)
You may want to use .forEach to call a method on returned results, not ['forEach']:
Object.getOwnPropertyNames(window).forEach(function (propName) {
console.log('In global window scope: ', propName);
});

Use prompt to generate table and add content to it based on input

I need to use Javascript to generate a table from user input in a prompt window.
This is for homework and we haven't covered things like jQuery or function scripting, all we've done is basic calculation scripts and the teacher has asked that we use a similar method to what we've been taught to solve the issue.
I have Googled and tried to solve it from what I found, but I don't particularly want to use methods we haven't been taught just yet, and the one method I found that does work is far more advanced than what we've done in class. And I just know that if I ask the teacher he won't be very helpful.
This is what I've got so far, and it generates a list of the input times table up to 10, but I need that data to end up in a table, all I need to know is where do I need the document.write tags to generate the numbers into a table?
Can it be done with some simple commands? Or is it more advanced than what we've been taught so far?
<html>
<body bgcolor=#66ccff text=#ff6600>
<script type="text/javascript">
var number = prompt("Please enter a number:");
for (i=1; i <= 10; i++)
{document.write( number + " x " + i + " = " + i*number + "<br>");};
</script>
</body>
</html>
What about this way:
<html>
<body bgcolor="#66ccff" text="#ff6600">
<script type="text/javascript">
var number = prompt("Please enter a number:");
document.write('<table border="1">');
for (i=1; i <= number; i++) {
document.write('<tr><td>' + number + " x " + i + "</td><td>=</td><td>" + i*number + "</td></tr>");
};
document.write('</table>');
</script>
</body>
</html>
I just assigned 2 to undefined number so at first run you don't have the error
<script type="text/javascript">
var number = prompt("Please enter a number:");
if(number == undefined)
number =2;
for (i=1; i <= 10; i++)
{document.write( number + " x " + i + " = " + i*number + "<br>");};
</script>
jsbin link is here: https://jsbin.com/puvitinaxi/edit?html,output

JavaScript/HTML/CSS - Multiple forms on one page

I'm trying to create a simple web page in JavaScript, HTML, and CSS. The web page generates 5 div elements. Each div element includes a random number, text input, and submit button. My code below does that.
The user then should be able to enter the random number into the text input box and click the submit button. The script should check if they entered the correct answer or not.
I'm not sure if this is possible? I understand how to write the code for just a single form on the page but this example is using 5 forms on a single page that are dynamically generated. Any help would greatly be appreciated.
<html>
<head>
<style type="text/css">
#test {
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
}
</style>
</head>
<body>
<script>
for (i = 0; i < 5; i++) {
document.write('<div id="test">');
var ranNum = Math.floor(Math.random()*10);
document.write(ranNum);
document.write("<p>Enter the number above:</p>");
document.write("<form id=\"form1\" name=\"form1\" method=\"post\" action=\"\"><input type=\"text\" name=\"answer\" id=\"answer\" /><input type=\"submit\" name=\"button\" id=\"button\" value=\"Submit\" /></form>");
document.write('</div>');
}
</script>
</body>
</html>
You don't even interact with the server to check if it was the correct answer.
So, yes, you can easily do that.
Use jquery, make those numbers properties to a global object, properties named after #id of your inputs, so when user clicks, just compare the value of input with the property of your global object with the same name.
eg:
window.myObject = {}
myObject.div1 = // your code for random number
myObject.div2 = // again, code for random number
And so on, even better put your random number code into a function and call
it for each property.
then just set the divs values as properties:
$("div.div1").append("<span class='value'>" + myObject.div1 + "</span>");
Or maybe even you could create a loop to do it so you don't need to type it for all divs.
After that, test your inputs:
$("div.div1").find("submit").click(function(){
// here you collect the data from your form, lazy to type
// and test it for equality with coresponding myObject.div1
// or with the value in <span class="value>
//e.g.
if ($(this).parent().find(".mytextinput").val() == $(this).parent().find("span.value").val())
{ //do something} else {//do something else }
});
Of course, this presumes you can use jquery.
as has been pointed out in the comments, make sure id's are always unique. I wouldn't use ajax for something this simple, you can check the values client side. See below for a working solution.
for (i = 0; i < 5; i++) {
document.write('<div id="div-' + i + '">');
var ranNum = Math.floor(Math.random()*10);
document.write(ranNum);
document.write("<p>Enter the number above:</p>");
document.write("<form id=\"form-" + i + "\" name=\"form-" + i + "\"><input type=\"text\" name=\"answer\" id=\"answer-" + i + "\" /><input type=\"submit\" name=\"button\" id=\"button-" + i + "\" value=\"Submit\" onclick=\"checkAnswer(this); return false;\"/></form>");
document.write('</div>');
}
function checkAnswer(element) {
var thisAnswer=element.form.parentElement.textContent.substring(0,1);
var answerGiven=element.form.children[0].value;
if (thisAnswer==answerGiven) {
alert("correct!");
} else {
alert("wrong!");
}
}

Can someone tell me if they see this

I am having problems when I try to pull it up on my computer the page is blank. I am not understanding this. Like when you click on the file button on the internet and you click open file that file shows up blank. Can someone help me understand why it is doing that. Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Week 10</title>
<script type="text/javascript">
/ *<![CDATA[ */
Var name;
firstName = "Valerie";
lastName ="Shipbaugh";
var placeOfBirth;
name=FirstName +"";
name += lastName;
placeOfBirth ="Houston";
placeOfBirth +=",Texas";
nameArray = name.split("");
/*]]>*/
</script>
</head>
<body>
<script type="text/javascript">
//<![CDATA[
document.write("<p> My first name is : + nameArray[0]
+ "<br />");
document.write("My last name is: "+ nameArray[1]
+ "<br />");
*/
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern matching rules ina regular experession.
*/
document.write("There are " + firstName.length
+ " characters in my first name" + " <br/>");
*/
This one called the length property.
This returns the number of characters in a string.
*/
document.write("I was born in " + placeOfBirth + " <br/>");
*/
With this string we are using concatenation operations.
*/
document.write("<p>My initials are: " + firstName.charAt(0) +
lastName.charAt(0) + "</p>");
*/
The last one return the character at the specific position in a text string
returns an empty string if the specified position is greater than the length of the string.
*/
//]]>
</script>
</body>
</html>
So where my comments are to explain what is going on is in the wrong place???
There is a more general way to solve this problem:
Take everything out of this file and
copy it into notepad.
Put just the
<html>and </html> into the file
Begin copying very small blocks into
the file one at a time, each time
reload the page
Soon you will see
one small block that causes the
failure, then you can assess that
small block.
Look at errors reported by the browser (tools->error console in firefox for example) it will hi-light errors such as you mismatched /**/ comments & the missing closing quote character from;
document.write("<p> My first name is : + nameArray[0]
Also js is case sensitive so its var not Var, which you should use to define all your variables such as firstname (which you incidentally later refer to as Firstname) etc.
Of course it won't work, the comment blocks aren't even right:
*/
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern
matching rules ina regular experession.
*/
Should be:
/*
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern
matching rules ina regular experession.
*/
Also, you really should avoid using document.write. In certain cases, that is what causes a blank page (if I remember correctly, when you use it after page load).
JavaScript is case sensitive - so in the first section of your scripts:
Var name; //var is with a lowecase "v"
firstName = "Valerie";
lastName ="Shipbaugh";
var placeOfBirth;
name=FirstName +""; //firstName was created with a lowecase "f"
Later you have this...
document.write("<p> My first name is : + nameArray[0]
+ "<br />");
You're missing a quote in there, should be
document.write(" My first name is : " + nameArray[0]
+ "");
And finally, comments open and close like this:
/* comment */
Not like this
*/ error */
Fixing these things will make the script run. However, it's not doing what I suspect you want. You are trying to split() the string containing the name, but there's nothing to split it on. You need to add a space between then and try this:
nameArray = name.split(" ");
You can see this working here:
http://jsfiddle.net/CM7fx/
Test in multiple browsers and make sure you have javascript enabled id' suggest first
The comments were wrong, the variable name are case sensitive. Here is a working version without comments, you can re-add those
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Week 10</title>
<script type="text/javascript">
var name;
var firstName = "Valerie";
var lastName ="Shipbaugh";
var placeOfBirth;
name= firstName + " " + lastName;
placeOfBirth ="Houston ,Texas";
var nameArray = name.split(" ");
</script>
</head>
<body>
<script type="text/javascript">
document.write("<p> My first name is : " + nameArray[0] + "<br />");
document.write("My last name is: " + nameArray[1] + "<br />");
document.write("There are " + firstName.length + " characters in my first name" + " <br/>");
document.write("I was born in " + placeOfBirth + " <br/>");
document.write("<p> My initials are: " + firstName.charAt(0) + lastName.charAt(0) + "</p>");
</script>
</body>
</html>

Categories