I want to ask about the form in Javascript.
I want to do a game where the user enters the correct word, then an alert message will appear for this correct word. When the user does the first word correct, the program will display another word (to be corrected). But the problem which I faced that I can't make the form display again to continue the game.
I used:
var d = document.getElementById("form1"); d.style.visibility = "visible";
but it doesn't work!
This is my code:
<head>
<title>Word Decoder</title>
<script type="text/javascript">
function checkWord(word, score)
{
var ok = words[score].valueOf();
var ok1 = document.getElementById("wordid");
if(ok1.value == ok)
{
score ++;
alert("Correct, your score is: " + score);
var d = document.getElementById("form1");
d.style.visibility = "visible";
return false;
}
else
{
alert("Wrong Spelling");
return false;
}
}
</script>
</head>
<body>
<script type="text/javascript">
var words = new Array ("apple", "orange", "banana", "manago", "table");
var reWords = new Array ("alpep", "ergano", "aaabnn", "goamna", "lbeat");
var count = 0;
var score = 0;
"</br>";
</script>
<form id="form1">
<br>
<dir id="displayForm"
style="position: relative;
visibility: visible;
display: block">
<h3><b> <script> document.write(reWords[score]);</script> </b></h3>
<br>
Enter the correct word: <input type="text" value="" id="wordid"/>
<input type="submit"
value="Check Answer ??"
onclick="return checkWord(wordid, score);" />
</dir>
</form>
</body>
Again: I want the game will display a scrambled word and the user must unscrambled the word to move to the other word. The problem is I can't display the form again to make the user unscrambled the second, third etc. words.
Use d.style.display="none" to hide and d.style.display="block" to show.
Think your post got mangled, I don't see where you are hiding it in the first place.. Also, avoid using document.write if you don't need it... inject the element or use .innerHTML if you need to, but not document.write.
Related
This discussion is the spin off of this post:passing-variables-between-pages,
I have edited the question in order to provide More clarity on the scripts, please who will give any answers to use denomination used in this version.
A.html
<form action="b.html"> // username field, let's say "Macbeth"
<input type="text" id="txt"/>
<input type="submit" value="nome" onClick="passvalues();"/>
</form>
<span id="result">Macbeth</span> // display username
<script>
function passvalues()
{
var nme = document.getElementById("txt").value; // set var username nme = textvalue
localStorage.setItem("textvalue", nme);
return false;
}
</script>
It works set localStorage and display it.
B.html
// show the username multiple times in an html text.
<p><strong><span class="result">Macbeth</span></strong>, Nice name!
It's the first time I've heard it! mmm...and tell me<strong>Macbeth<span class="result"></span></strong> which gender you are?</p>
<form name="genderForm" action="">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="neutral"> Neutral
</form>
// form to obtain the gender chosen by the user, let's say "male"
`<p>I am a <span class="selectedGender"></span> of course!</p>`
// display the selected gender
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
var rad = document.genderForm.gender;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
(prev) ? console.log(prev.value) : null;
if (this !== prev) {
prev = this;
}
console.log(this.value);
document.getElementsByClassName("selectedGender")[0].innerHTML = this.value;
localStorage.setItem("gender", this.value);
});
}
</script>
<script>
var selectedGender = document.getElementsByClassName('selectedGender');
{
className.innerHTML = localStorage.getItem("textvalue");
};
</script>
It works, display the selected gender.
C.html
I am really, really sorry but I am completely lost and confused here.
I tried several times one of the suggested by solutions:
<span id="welcome"></span> to page 4 <span id="name"></span>
<script>
var username = localStorage.getItem("textvalue");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('welcome').innerHTML = 'brava';
}else if (usergender === 'male'){
document.getElementById('welcome').innerHTML = 'bravo';
}else{
document.getElementById('welcome').innerHTML = 'bene';
}
</script>
I know I'm a hopeless case, I don't understand it.
In which page do I have to insert this script?
this script replaces the previous ones?
Can't I use the same scripting used for the username?
1 - get the choice:"selectedgender"
2 - display it with (of course changing the elements names)
<script>
function passvalues()
{
var nme = document.getElementById("txt").value; // set var username nme = textvalue
localStorage.setItem("textvalue", nme);
return false;
}
</script>
3 - and show with:
<span id="result">Macbeth</span> // display username
Thanks for the attention.
To make life a little easier for you, I re-wrote your scripts using slightly different variable names that make a little more sense. I tested these; they work. If you print both sets and compare these NEW scripts with the older scripts, you can see a little more clearly how it all works.
Page A:
<form action="b.html">
<input type="text" id="txt"/>
<input type="submit" value="nome" onClick="passvalues();"/>
</form>
<span id="result"></span>
<script>
function passvalues(){
var nme = document.getElementById("txt").value; // set var username nme = youzer
localStorage.setItem("youzer", nme);
return false;
}
</script>
Page B:
<!-- show the username multiple times in an html text. -->
<p>Hello, <strong><span class="uname">Macbeth</span></strong>, Nice name!</p>
<p>It's the first time I've heard it! mmm...and tell me, <strong><span class="uname"></span></strong>, which gender you are?</p>
<form name="genderForm" action="">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="neutral"> Neutral
</form>
<p>I am a <span class="selectedGender"></span> of course!</p>
<script>
/* Schlep stored name into all elements with className "uname" */
var unamez = document.getElementsByClassName('uname');
[].slice.call(unamez).forEach(function (className) {
className.innerHTML = localStorage.getItem("youzer");
});
var frmGender = document.genderForm.gender;
var prev = null;
for (var i = 0; i < frmGender.length; i++) {
frmGender[i].addEventListener('change', function () {
(prev) ? console.log(prev.value) : null;
if (this !== prev) {
prev = this;
}
console.log(this.value);
document.getElementsByClassName("selectedGender")[0].innerHTML = this.value;
localStorage.setItem("gender", this.value);
//Delay 2 seconds, then go to page (C)
setTimeout(function(){
window.location.href = 'c.html';
},2000);
});
}
</script>
Page C:
<span id="greetz"></span> to page 4, <span id="name"></span>!
<p></p>Return to page A</p>
<script>
var username = localStorage.getItem("youzer");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
// Below commented out because <span id="gender"> does not exist on page
// document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('greetz').innerHTML = 'Brava';
}else if (usergender === 'male'){
document.getElementById('greetz').innerHTML = 'Bravo';
}else{
document.getElementById('greetz').innerHTML = 'Bene';
}
</script>
Note that these code snippets don't "work" on StackOverflow - the Run Code Snippet buttons won't do anything. I used the Code Snippet system only to allow the three code groups to be hidden until expanded, for neatness. You must copy each one out and paste it into a file in your dev environment to make them work (all three must be present on your system before running them).
Your page3.html can be as below:
<!DOCTYPE html>
<html>
<head>
<title>Page 3</title>
</head>
<body>
<p><span id="name"></span>, please select your gender.</p>
<a id="Male" href="page4.html" onclick="saveSelectedGender(this)">Male</a><br/>
<a id="Female" href="page4.html" onclick="saveSelectedGender(this)">Female</a><br/>
<a id="Neutral" href="page4.html" onclick="saveSelectedGender(this)">Neutral</a><br/>
<script>
document.getElementById('name').innerHTML = localStorage.getItem("textvalue");
function saveSelectedGender(ele) {
localStorage.setItem('gender', ele.id);
}
</script>
</body>
</html>
and your page4.html can be as below:
<!DOCTYPE html>
<html>
<head>
<title>Page 4</title>
</head>
<body>
<p><span id="name"></span>, your selected gender is: <span id="gender"></span>.</p>
<script>
document.getElementById('name').innerHTML = localStorage.getItem("textvalue");
document.getElementById('gender').innerHTML = localStorage.getItem("gender");
</script>
</body>
</html>
Notice this line on page two:
localStorage.setItem("gender", this.value);
It is almost exactly the same as the line on page 1 that stores the user name:
localStorage.setItem("textvalue", nme);
In your hidden localStorage, you now have two variables: gender and textvalue, and each of them stores some information. Check it for yourself - there is a way to view the localStorage area:
INSTRUCTIONS FOR GOOGLE CHROME:
1. Run your app, and enter the data on both page 1 and page 2.
2. Press <kbd>F12</kbd> (or, right-click on the page and choose `Inspect Element`)
3. "Developer Tools" will open.
4. Note the menu at top that begins: `Elements | Console | Sources | Network >>`
If the last menu item is `>>` then click that - additional menu choices will drop-down
5. You want the menu item `Application` - click on that
6. You will see 5 groupings on the left: Application, Storage, Cache, Background... etc
7. In the Storage group, do you see `Local Storage`? That's what we want!
8. Click the drop-down triangle beside (at the left) "Local Storage"
9. Now, in the right side panel, you should see your "hidden" variables, and their current values
No matter what HTML page you are on (of your project), you can see those same variables - so you can tell your script to read those variables.
So, on pages 3 and 4, write some javascript (the code is below) that will:
(a) read a localStorage value and store it in a new variable
(b) select the appropriate element (div, span, p, etc) on that page
(c) stick the variable data into the element.
(d) repeat for the other localStorage entry
The reason why the existing javascript code didn't work is because it was written for page2, where the target element is called class="result". Note the first line of the javascript:
var bob = document.getElementsByClassName('result');
(I changed the name of the variable because that name doesn't matter - what matters is getElementsByClassName('result')). If there is no element on the page with class="result", the javascript will fail right there. So, on pages 3 and 4, death!
On page 4, then, you can do this:
<span id="welcome"></span> to page 4 <span id="name"></span>
<script>
var username = localStorage.getItem("textvalue");
var usergender = localStorage.getItem("gender");
document.getElementById('name').innerHTML = username;
document.getElementById('gender').innerHTML = usergender;
if (usergender === 'female'){
document.getElementById('welcome').innerHTML = 'brava';
}else if (usergender === 'male'){
document.getElementById('welcome').innerHTML = 'bravo';
}else{
document.getElementById('welcome').innerHTML = 'bene';
}
</script>
Final Notes:
The reason you do not need this nifty bit of code:
[].slice.call(result).forEach(function (className)...
is because THIS code var result = document.getElementsByClassName('result')
creates a list (an array) of all the elements with the className result. Then the .slice code loops through that array and schleps the username into each and every element.result. Only on page 2 do you have an element (well, two elements) with the className "result". On page 3 (NO className "result") elements, the code fails.
I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.
I am trying to use JavaScript in an online examination assignment in HTML. As a requirement of the project, we have to use text input forms as well as radio buttons and the like. I have dealt with the part of radio buttons but for some reason my text input forms do not work. My problem will be clearly stated using this code snippet from the main project:
<html>
<head>
<title></title>
<script type="text/javascript">
var test, name, matr, myname, count = 0;
function form(){
test = document.getElementById("test");
test.innerHTML = "Count = "+count;
test.innerHTML += "<form> \
First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check(){
myname = document.getElementsByName("name");
if (myname[1].value == "myname")
{
count++;
}
form();
}
window.addEventListener("load", form, false);
</script>
</head>
<body>
<div id = "test"></div>
</body>
</html>
What this code aims to do is that when the user inputs "myname" into the form called 'First name' and clicks 'Submit', the counter on the top should increment.
Can someone please shed some light on what I am doing wrong and how it may be resolved.
As Pluto mentioned, arrays in javascript start at 0. You can also look at tinkering with the form element. It is not closed nor is the type, get or post specified. I got it working in the example below by removing the form completely. This is because the button press was trying to submit the form and therefore load a new page.
https://jsfiddle.net/jpm68eub/
var test, name, matr, myname, count = 0;
function form() {
test = document.getElementById("test");
test.innerHTML = "Count = " + count;
test.innerHTML += "</br> First name:<br> \
<input type='text' name='name'><br>\
<button onclick='check()'>Submit Answer</button>";
}
function check() {
myname = document.getElementsByName("name");
if (myname[0].value == "myname") {
count++;
}
form();
}
form();
you need to prevent the default action of the onclick event. To do this, try something like this:
function check(e){
e.preventDefault();
myname = document.getElementsByName("name");
if (myname[0].value == "myname")
{
count++;
}
form();
}
the above user was also correct about where javascript arrays start (they start at 0)
Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim
I am trying to create a simple HTML program that will allow the user to input a number or word, then if the userInput matches what I have defined, it changes that input to something else, then outputs the new value on the screen.
Also looking for a button to reset the program (at any time to start over)
Any ideas?
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test() {
var userInput = document.getElementById("userInput").value;
//Need to add If, else if, else to change the value of userInput
// for example, If xxxx value, set to yyyy, then output yyyy
document.write(userInput);
}
// Need to add a "reset" to go back to restart the program
</script>
</body>
</html>
Working better now with... but where does the reset go? How do I format the output? all noob questions yes
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
userInput="yyyy";
}
else if(userInput == "yyyy") {
userInput="zzzz";
}
else {
userInput="Not Found";
}
document.write(userInput);
}
// Need to add a "reset" to go back to restart the program
</script>
</body>
</html>
Convert the function to the following.
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
// I forgot the updating part here.
document.getElementById("otherIdToWriteOutput").innerHTML = "yyyy";
}
}
You can also add the reset button. And remove the current text using
document.getElementById("id").innerHTML = ""; // remove the inner html.