Please check out the code below. I want to get the value entered in the prompt box into function dis(). How can I do that?
<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var z=prompt("enter your name...");
if(z!=null)
{
document.getElementById("demo").innerHTML="thankyou"+z+"..";
document.getElementById("case").style.display='block';
}
else
document.getElementById("demo").innerHTML="thankyou";
}
function dis()
{
var a=document.getElementById("aaa").value;
alert("your mark is"+a);
}
</script>
</head>
<body>
<p id="demo">click on the button.....</p>
<button type="button" onclick="display()">submit</button>
<div id="case" style="display:none">
<input type="text" id="aaa" name="myText" onDblClick="dis()">enter your mark
</div>
</body>
</html>
If you want to directly pass value to dis() function then change your script to
function display() {
var z = prompt("enter your name...");
if (z != null) {
document.getElementById("demo").innerHTML = "thankyou " + z + "..";
document.getElementById("case").style.display = 'block';
dis(z);
}
else
document.getElementById("demo").innerHTML = "thankyou";
}
function dis(arg) {
alert("your mark is" + arg);
}
If you want the value to be accessible from independent functions you'll need to store it in a global variable:
<script>
var userName = null;
function display() {
userName = prompt("enter your name...");
if (userName != null) {
document.getElementById("demo").innerHTML="thankyou "+userName +"..";
document.getElementById("case").style.display='block';
} else
document.getElementById("demo").innerHTML="thankyou";
}
function dis() {
var a=document.getElementById("aaa").value;
alert(userName + ", your mark is"+a);
}
</script>
Note that if the functions are completely independent they'll all need to test whether the variable has a value yet. In your case the dis() function is only called from a control that is made visible after a value has been set, but note that the user might click the button again and then cancel - in which case the name will be set back to null but the case element will still be visible.
Related
In this project, I need to set a maximum of 10 guesses, an indication of what number is being guessed and keep those results on the screen at the end of each game without overwrite the previous guesses.
Each set of guess output needs to be numbered to indicate how many guesses have been made. For the output, I need to use innerHTML. The user will guess a number from 1 to 999. I have to use while loop.
So far this is the code where I'm working and I have some errors and it's not working. Can anybody put me in the right direction to finish this code?
The errors that I found when I inspect the document are checkGuess() function and an anonymous function with a message "Cannot read property 'value' of null"
<script type="text/javascript">
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.getElementById("guesses");
var lastResult = document.getElementById("lastResult");
var lowOrHi = document.getElementById("lowOrHi");
var guessSubmit = document.getElementById("guessSubmit");
var guessField = document.getElementById("guessField");
var guessCount = 1;
function checkGuess() {
var userGuess = Number(guessField.value);
guesses.innerHTML += userGuess + "";
}
while (guessCount == 10) {
lastResult.innerHTML = "!!!GAME OVER!!!";
disableForm();
} else {
if (userGuess == randomNumber) {
lastResult.innerHTML = "Congratulations! You got it right!";
lowOrHi.innerHTML = "";
disableForm();
} else {
lastResult.innerHTML = "Wrong!";
if (userGuess < randomNumber) {
lowOrHi.innerHTML = "Your guess is too low!";
} else if (userGuess > randomNumber) {
lowOrHi.innerHTML = "Your guess is too high!";
}
}
guessCount++;
guessField.value = "";
}
}
function disableForm() {
var wholeForm = document.querySelector(".form"); // grab a reference to the whole form (the contents of the div with class form)
wholeForm.style.opacity = 0.5; // change the opacity of the form to 0.5
guessField.setAttribute("disabled", "disabled");
guessSubmit.setAttribute("disabled", "disabled"); // disable the form field and submit button so they can no longer be used
}
guessSubmit.onclick = checkGuess;
</script>
</head>
<body>
<h1>Number guessing game</h1>
<p id="guesses"></p>
<p id="lastResult"></p>
<p id="lowOrHi"></p>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit">Enter Guess</button>
</div>
<p></p>
</body>
</html>
Your program is all wrong and is actually doing nothing
the only thing that actually executes is everything outside your functions,
and those are being called only when the page is loaded for first time
in order to execute your CheckGuess you need to actually call it :
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
but everything else that is actually outside of your functions are only executed when the page is loading
also you have a while--else statement, that's not even possible
then again... it is outside a function so it is useless
You need to put everything on one single statement
YOU DO NOT NEED A WHILE
once you write something down on the page it will stay there until it reloads
if you write a while like that you will just loop your code endless.
this code and logic is so wrong in so many ways i will sent you a functional code :
<script type="text/javascript">
var guesscount =0;
var randomNumber = Math.floor(Math.random() * 100) + 1;
function checkGuess()
{
guesscount = guesscount +1;
var userGuess = document.getElementById("guessField").value;
document.getElementById('guesses').innerHTML += Number(userGuess)+ '<br>';
CheckResults();
}
function CheckResults()
{
//add here your logics if the number is wrong
if ( guesscount>= 10)
{
document.getElementById("guessField").disabled = true;
document.getElementById("guessSubmit").setAttribute('disabled', 'disabled');
document.getElementById('guesses').innerHTML += 'game Over !';
}
}
</script>
</head>
<body>
<h1>Number guessing game</h1>
<label id="guesses"></label>
<label id="lastResult"></label>
<label id="lowOrHi"></label>
<div class="form">
<label for="guessField">Enter your next guess: </label>
<input type="text" id="guessField">
<button id="guessSubmit" onclick="checkGuess() ">Enter Guess</button>
</div>
<p></p>
</body>
</html>
what is problem with this script? i just want to show checkbox status in innerHTML that show "yes" after click on button, if it is checked, otherwise it shown "no".
<html>
<body>
<p id="demo"></p>
<input id="chkbox" type="checkbox" name="Terms" value="agree" ><br>
<input type="button" value="button" onClick="myFunction()" >
<script>
function myFunction() {
var box = document.getElementById("chkbox");
if(checkbox.checked)
{
var checked.value = "yes";
var txt = checked.value;
document.getElementById("demo").innerHTML = txt;
}
else if(checkbox.unchecked)
{
var unchecked.value = "no";
var txt = unchecked.value;
document.getElementById("demo").innerHTML = txt;
}
}
</script>
</body>
function myFunction() {
var box = document.getElementById("chkbox");
if(box.checked)
{
document.getElementById("demo").innerHTML = 'yes'
}
else
{
document.getElementById("demo").innerHTML = 'no';
}
}
The problems in your code were:
You set the variable box, but then used checkbox.checked instead of box.checked.
You looked for checkbox.unchecked. There's no such property; if .checked isn't true, then the box is unchecked.
You tried to declare variables checked.value and unchecked.value. Variable names can't contain ., that's used for specifying object properties when accessing a variable whose value is an object.
There are multiple problems.
There is no variable with the name checkbox
The syntax var checked.value = "yes"; is invalid
Try
<input type="button" value="button" onClick="myFunction()">
then
function myFunction() {
var box = document.getElementById("chkbox");
box.value = box.checked ? "yes" : 'no';
document.getElementById("demo").innerHTML = box.value;
}
Demo: Fiddle
Since jQuery tag is used include jQuery library in the page then
<input type="button" value="button" id="button">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and
//dom ready handler
jQuery(function ($) {
//cache the elements for future use
var $chk = $('#chkbox'), // id-selector
$demo = $('#demo');
//click event handler
$('#button').click(function () {
//use is() and :checked-selector to check whether the checkbox is checked and use .text() to set the display text of the p element
$demo.text($chk.is(':checked') ? 'yes' : 'no')
})
})
Demo: Fiddle
try:
You assigned element to box not to checkbox
There is nothing like checkbox.unchecked
var name checked.value is not correct format.
Here is code:
function myFunction() {
var box = document.getElementById("chkbox");
if (box.checked) {
document.getElementById("demo").innerHTML = "yes";
} else {
document.getElementById("demo").innerHTML = "no";
}
}
Here is working Demo
Check this one
function myFunction() {
if(document.getElementById('chkbox').checked) {
alert("checked");
} else {
alert("not checked")
}
}
try something like this,Shorthand
function myFunction(){
var box = document.getElementById("chkbox").checked;
document.getElementById("demo").innerHTML = box ? 'yes' : 'no';
}
I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
I'm making a quiz with a text input. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function check() {
var s1 = document.getElementsByName('s1');
if(s1 == 'ō') {
document.getElementById("as1").innerHTML = 'Correct';
} else {
document.getElementById("as1").innerHTML = 'Incorrect';
}
var s2 = document.getElementsByName('s2');
if(s2 == 's') {
document.getElementById("as2").innerHTML = 'Correct';
} else {
document.getElementById("as2").innerHTML = 'Incorrect';
}
//(...etc...)
var p3 = document.getElementsByName('p3');
if(p3 == 'nt') {
document.getElementById("ap3").innerHTML = 'Correct';
} else {
document.getElementById("ap3").innerHTML = 'Incorrect';
}
}
</script>
</head>
<body>
1st sing<input type="text" name="s1"> <div id="as1"><br>
2nd sing<input type="text" name="s2"> <div id="as2"><br>
<!-- ...etc... -->
3rd pl<input type="text" name="p3"> <div id="ap3"><br>
<button onclick='check()'>Check Answers</button>
</body>
</html>
Every time I check answers it always says Incorrect and only shows the first question. I also need a way to clear the text fields after I check the answers. One of the answers has a macro. Thanks in advance.
The method getElementsByName returns a NodeList, you can't really compare that against a string. If you have only one element with such name, you need to grab the first element from that list using such code instead:
var s1 = document.getElementsByName('s1')[0].value;
To make it more flexible and elegant plus avoid error when you have typo in a name, first add such function:
function SetStatus(sName, sCorrect, sPlaceholder) {
var elements = document.getElementsByName(sName);
if (elements.length == 1) {
var placeholder = document.getElementById(sPlaceholder);
if (placeholder) {
var value = elements[0].value;
placeholder.innerHTML = (value === sCorrect) ? "Correct" : "Incorrect";
} else {
//uncomment below line to show debug info
//alert("placeholder " + sPlaceholder+ " does not exist");
}
} else {
//uncomment below line to show debug info
//alert("element named " + sName + " does not exist or exists more than once");
}
}
Then your code will become:
SetStatus('s1', 'ō', 'as1');
SetStatus('s2', 's', 'as2');
//...
document.getElementsByName('s1') is an array you should use document.getElementsByName('s1')[0] to get certain element(first in this case)
I'm having a problem with the following code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
<!--
gallows = new Array("--------\n| |\n|\n|\n|\n|\n=====",
"--------\n| O\n|\n|\n|\n|\n=====",
"--------\n| O\n| |\n|\n|\n|\n=====",
"--------\n| O\n| \\|\n|\n|\n|\n=====",
"--------\n| O\n| \\|/\n|\n|\n|\n=====",
"--------\n| O\n| \\|/\n| |\n|\n|\n=====",
"--------\n| O\n| \\|/\n| |\n| /\n|\n=====",
"--------\n| O\n| \\|/\n| |\n| / \\\n|\n=====");
guessChoices = new Array("JavaScript", "Navigator", "LiveConnect", "LiveWire");
guessed = [];
function startAgain()
{
guesses = 0;
max = gallows.length - 1;
//guessed = " ";
len = guessChoices.length - 1;
toGuess = guessChoices[Math.round(len*Math.random())].toUpperCase();
displayHangman();
displayToGuess();
displayGuessed();
}
function stayAway()
{
document.game.elements[3].focus();
alert("Don't mess with this form element!");
}
function displayHangman()
{
document.game.status.value=gallows[guesses];
}
function displayToGuess()
{
pattern = "";
for(i=0;i<toGuess.length;++i)
{
if(guessed.indexOf(toGuess.charAt(i)) != -1)
pattern += (toGuess.charAt(i)+" ");
else pattern += "_ ";
}
document.game.toGuess.value=pattern;
}
function displayGuessed(s)
{
result="";
for(i in s)
{
guess=s[i];
result += guess;
}
document.game.guessed.value=result;
//document.game.guessed.value=guessed;
}
function badGuess(s)
{
if(toGuess.indexOf(s) == -1) return true;
return false;
}
function winner()
{
for(i=0;i<toGuess.length;++i)
{
if(guessed.indexOf(toGuess.charAt(i)) == -1) return false;
}
return true;
}
function guess(s)
{
if(guessed.indexOf(s) == -1) guessed.push(s);
if(badGuess(s)) ++guesses;
displayHangman();
displayToGuess();
displayGuessed(guessed);
if(guesses >= max)
{
alert("You're dead. The word you missed was "+toGuess+".");
startAgain();
}
if(winner())
{
alert("You won!");
startAgain();
}
}
// -->
</script>
</head>
<body>
<h1>Hangman</h1>
<form name="game">
<pre>
<textarea name="status" rows="7" cols="16" onfocus="stayAway();"></textarea>
</pre>
<p>
<input type="text" name="toGuess" onfocus="stayAway();"> Word to guess<br>
<input type="text" name="guessed" onfocus="stayAway();"> Letters guessed so far<br>
</p>
<p>Enter your next guess.</p>
<p>
<input type="text" name="input" size=1 value="">
<input type = "button" value = "guess" onclick = "guess(game.input.value); game.input.value = '';">
</p>
<input type="button" name="restart" value="---- Start Again ----" onclick="startAgain();">
<script type="text/javascript">
<!--
startAgain();
// -->
</script>
</form>
</body>
</html>
After I click the game.guess button, the first time around, I get the expected output... game.input clears and guessed is displayed. However, the second time I click the guess button with a different value, I receive the error:
guess is not a function
| onclick()
| event = click clientX=77, clientY=33
guess(game.input.value) onclick(line 2)
And I honestly can't figure out why. What am I doing wrong?
(I got the bulk of this code from Mastering JavaScript, Premium Edition, by James Jaworski)
The problem is on these lines:
guess=s[i];
result += guess;
This way you are changing the context of guess. If you change this line to
result += s[i];
Your error will go away.
You are conflicting your function with using same name for a variable.
Remember to define your variables using var keyword and avoid such confusion.
1 - use anonymous functions where possible
2 - declare and use local variables
To avoid conflicts.
In your function displayGuessed(), you are setting the variable guess (which is a function) to the the guessed letters.
You can fix this by defining your function's guess variable (making it distinct from the function) using the "var" keyword:
function displayGuessed(s)
{
var guess;
result="";
for(i in s)
{
guess=s[i];
result += guess;
}
document.game.guessed.value=result;
}
Tip: I found this bug easily by using the Firebug plugin for firefox, which lets you step through javascript code line by line, to see where things are going wrong.