Catching value of text box using JavaScript - javascript

I'm trying to have a button and text box displayed. Have the user enter a number. That a random number will be generated and the user has 10 attempts to answer the question correctly. The script should check whether the users number is either equal to, less than, or greater than the random number. I am having trouble getting the number inputted from the text-box.
HTML:
<form name="myForm">
<div id='myForm'></div>
</form>
JAVASCRIPT:
function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
var check = document.getElementById('textbox').value
button.onclick = calc(guessCount, random, check);
}
function calc(guessCount, random, check){
while(guessCount > 0) {
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;
}
}

Your code is assigning callback function result to onclick event instead of function itself. Besides, you are also trying to run a while loop which will consume guessCount on first click event.
I edited code, following should work:
function partC(){
var guessCount = 10;
var random = Math.round(Math.random()*100);
var button = document.createElement('input');
button.type = "button";
button.value = " Guess! ";
document.getElementById('myForm').appendChild(button);
var textbox = document.createElement('input');
textbox.type = 'number';
document.getElementById('myForm').appendChild(textbox);
button.onclick = function(){
var check = textbox.value*1;
if (check == random){
alert("Correct!");
} else if (check > random) {
alert("Try Again. Guess to High. " + guessCount + " tries left.");
} else if (check < random) {
alert("Try Again. Guess to Low. " + guessCount + " tries left.");
}
guessCount--;
}
}

You are accessing the value by using id, whereas you didn't give any id to your input.
Try this:
textbox.id = 'textbox';

You forgot the set the id of your textbox element. Try adding the id after creating it. Then you can get the element by its id, which in your case is textbox

var myEl = document.getElementById('a');
myEl.addEventListener('click', function() {
alert(document.getElementById('text').value);
}, false);
<input type="text" id="text"/>
<button id="a">Alert text</button>

Jquery has a wonderful option available for you,
$('#unique-id').val();
The unique ID will be whatever value that specific textarea. So in this case:
<textarea id="unique-id"></textarea>

I just wanted to add this to what all the other answers say. You probably want a semicolon after this line:
var check = document.getElementById('textbox').value

Related

How to hold a value and pass it while creating dynamic textbox on html/javascript

Im doing a dynamic text box with javascript. But when I execute my button, the value I alredy inserted are erased. So like if I have one textbox and type something on it, when I execute the button to create another textbox it erase all I had type on the 1st one, and create the other one.
I understand why it is happening, but I dont know if there is a way to hold the value, and pass to the "new" div.
<script language="javascript">
var x = 1;
function Button()
{
my_div.innerHTML = my_div.innerHTML +"<label for='variation'>Carro " + x +": </label>" + "<input type='text' name='xcar"+ x +"'>"
x++;
}
</script>
So the problem as I said before was that the my_div.innterHTML was replacing himself and losing the values.
<script language="javascript">
window.onload = function () {
var createTextbox = function () {
var x = 1,
container = document.getElementById('my_div');
return function () {
var div = document.createElement('div');
input = document.createElement('input');
input.type= "text";
input.name = "xtext" + x;
div.appendChild(input);
container.appendChild(div);
x++;
}
}();
document.getElementById('createButton').onclick = createTextbox;
</script>
<input class="carbutton" type="button" value="+ Carro" id="createButton">
I just used this code instead.

Prevent Default not working, not sure why

I'm supposed to press enter to submit the form
my code doesnt work on this FIDDLE but it works on this one FIDDLE2.
I'm not really sure why and would like to see if anyone knows why. The code is exactly the same
var i = 0;
var allowed = /^[a-zA-Z0-9]+$/;
$('#form').submit(function(e) {
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if (!allowed.test(input)) {
alert("Name can have only letters and numbers.\n\n Names Already Submitted: " + ar.join(" , "));
return false;
} else {
ar[i] = input;
alert("Your name was successfully submitted\n\n Names Already Submitted: " + ar.join(" , "));
i = i + 1;
return false;
}
})
You have not included jQuery in the first fiddle, and that is why $ can not be resolved or defined error is there.
Second fiddle does includes jQuery and it is working as expected.
It is showing $ is not defined. It is means you are not including jQuery in your project.
add jQuery in your code. working fiddle here
Add
$('#form').submit(function(e){
e.preventDefault(); // Saves from Reloading of page
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if(!allowed.test(input)){
alert("Name can have only letters and numbers.\n\n Names Already Submitted: "+ ar.join(" , "));
return false;
}else{
ar[i]= input;
alert("Your name was successfully submitted\n\n Names Already Submitted: "+ ar.join(" , ") );
i = i+1;
return false;
}
});
try the below code
When the input is not matching your regex, then validation will occurs and page will get not submit.
use preventDefault in if (!allowed.test(input)) {
$('#form').submit(function (e) {
var input = $('#t_input1').val();
var ar = $('#t_input1').data('name');
if (!allowed.test(input)) {
alert("Name can have only letters and numbers.\n\n Names Already Submitted: " + ar.join(" , "));
e.preventDefault();
return false;
} else {
ar[i] = input;
alert("Your name was successfully submitted\n\n Names Already Submitted: " + ar.join(" , "));
i = i + 1;
return false;
}
})

rapid background change upon prompt answer

I am a noob here in JS and I am doing my homework making a simple color guessing game. So far everything works as far as the criteria goes.
My only problem is that I can't figure out how to make it so that the background changes instantly upon user input (Right after clicking [OK] at the Prompt). As of now with the code below, the background changes only after clicking [OK] in the Congrats alert..I am pretty sure it's possible because my prof showed in the lecture an example he did where the background color changed right after guessing the correct color!
Also, it would be nice if any pros out there could give me suggestions on polishing my code. I have a feeling that it is messy and too complex than what its trying to achieve..Heh..
PS: I know that js logic should be separated in the page but my prof insisted we do this exercise with the script inline!
Thank you!
<body onload="doGame()">
<script>
var myBody = document.getElementsByTagName("body")[0];
var target;
var answer;
var guessInputText;
var guessInput;
var finished = false;
var guessAmount = 0;
var colors = ['Salmon', 'Tomato', 'Moccasin', 'Peru', 'Olive', 'Teal', 'Navy', 'Thistle', 'Beige', 'Gray'];
var colorsSorted = colors.sort();
var colorsSortedString = colors.join(', ');
function doGame() {
var randomColorNum = Math.random() * 10;
var randomColorNumInt = Math.floor(randomColorNum);
target = colors[randomColorNumInt + 1];
answer = target.charAt(0).toLowerCase() + target.slice(1).toLowerCase(); //makes sure answer is in lowercase
alert("The answer is " + target + " or " + answer); //for debugging
while(!finished) {
guessInputText = prompt('I am thinking of one of these colors:\n\n' +
colorsSortedString + '\n\n' +
'What color am I thinking of?');
guessInput = guessInputText.charAt(0).toLowerCase() + guessInputText.slice(1).toLowerCase(); //converts whatever input into lowercase
guessAmount += 1;
finished = checkGuess(); //checks to see if user input is correct
}
}
function checkGuess() {
if ((colors.indexOf(guessInputText.charAt(0).toUpperCase() + guessInputText.slice(1).toLowerCase()) > -1) == false) {
alert("Sorry, I don't recognize your color.\n\n" +
"Please try again!");
return false;
}
if (guessInput > answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically higher than mine.\n\n" +
"Please try again!");
return false;
}
if (guessInput < answer) {
alert("Sorry, Your guess is incorrect!\n\n" +
"Hint: Your color is alphabetically lower than mine.\n\n" +
"Please try again!");
return false;
}
myBody.style.background = answer;
alert("Congratulations! You have guessed the color!\n\n" +
"It took you " + guessAmount + " guesses to finish the game!\n\n" +
"You can see the color in the background.");
return true;
}
</script>
</body>
If you want to modify the background before the [OK] on congrats prints, you just have to move this line
myBody.style.background = answer;
But.. Testing your snippet, the background change right after I press OK on the guess color prompt.
So what do you want exactly ? Can you give us an example step by step ?

I need to use a jQuery function to check the range of numbers and to see if it's validated and it's not working

I have just begun to learn how to use jQuery I need to validate an input field and test the range of numbers entered. I have written what I believe would be the correct way to do it but it doesn't work, in fact if you do enter a number between the range nothing occurs in the game. I would also like to have the input box turn "red" if the number entered isn't in the range, as well as put the output message I have included in my code if it doesn't fit.
This is my code:
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js">
</script>
<link rel="stylesheet" type="text/css" href="dice.css">
<title>Dice Game</title>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$('#guess').focus();
$('#roll').click(function () {});
$("#guess").validate({
rules: {
guess: {
required: true,
range: [2, 12]
}
}, //end of rules
message: {
guess: {
required: "Please enter a number.",
range: "You must enter a number between 2 and 12."
}
}
}); //end of validate()
var count = 3;
function startover() {
count = 3;
alert("Make a guess and click the Roll button.");
}
function roll(guess) {
if (count == 0) {
alert("Click the Play Again button.");
return;
}
var die1 = Math.floor(1 + 6 * Math.random());
var die2 = Math.floor(1 + 6 * Math.random());
var sum = die1 + die2;
if (guess == sum) {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". Congratulations, you win!");
count = 0;
} else {
--count;
if (count == 0) {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". You have no rolls left. " +
"Sorry... the computer won.");
} else {
alert("You rolled a " + die1 + " and a " + die2 +
" which adds up to " + sum + ". Your guess is " +
guess + ". You have " + count + " rolls left. " +
"Click Roll to try again.");
}
}
}
}); // end ready </script>
<form id="game">
<h1>Welcome to the dice game!</h1>
<p>Here's how it works! If you roll two dice and add up the values, you will get a minimum of 2 and a maximum of 12.</p>
<p>Enter a number between 2 and 12:
<input type="text" name="guess" id="guess" min="2" max="12" />
<br>The computer will roll the dice for you up to three times. If the dice match your guess, you win!</p>
<input type="button" value="Roll" onclick="roll(guess.value);" />
<input type="button" value="Play Again" onclick="startover();" />
</p>
</form>
</body>
</html>
There are these problems with your code:
javascript functions for button event handler should NOT be placed inside $(document).ready();
jQuery validate plugin should be run on your form element ($("#game").validate), NOT on your input text element ($("#guess").validate).
In order for invalid input to be highlighted, you need to add 'error' and 'valid' css styles.
In order to stop the game from proceeding, you can disable submit buttons when form validation fails, using:
onkeyup: function (element, event ) {
if(!$("#game").valid()) {
$(":button").attr("disabled", "disabled");
} else {
$(":button").removeAttr("disabled", "disabled");
}
}
Please see Plunker with working code.
Note: I haven't looked at your game logic, and haven't modified it, I have fixed the validation part.
validate is not a method in the jQuery core API and you are not linking to any other jQuery plugins. Looks like you are missing a SCRIPT tag for your validation plugin
You can do this with JavaScript. There's no need to specifically use jQuery for this.
With JavaScript, all you need to do is handle the 'roll' button click event:
var btnButton = document.getElementById('roll');
btnButton.addEventListener("click", function () {
var txtValue = document.getElementById('guess').value;
if (txtValue.length > 0) {
if (!isNaN(+txtValue)) {
if (txtValue > 2 && txtValue < 12) {
document.getElementById('spanValidationMsg').className = "hide";
//WRITE YOUR CUSTOM CODE HERE
//WRITE YOUR CUSTOM CODE HERE
}
else {
document.getElementById('spanValidationMsg').innerHTML = "You must enter a number between 2 and 12.";
}
}
}
else
{
document.getElementById('spanValidationMsg').innerHTML = "Please enter a number";
document.getElementById('spanValidationMsg').className = "show";
}
});
See this here: http://jsfiddle.net/jL26k/2/
EDIT: There was a small error. Check the link now.
The problem is your selector is wrong, you should be selecting the form element not the guess element.
e.g. it should be $('#game').validate({ ...
To get the form inputs to change color read the documentation here: http://jqueryvalidation.org/validate#errorclass

Accept user input and multiply by 0.00000116414, copy results to clipboard

This code pops up asking for the users input, and multiplies it by 0.00000116414.
I want to change this into a text input field and calc button, then perhaps add the ability to copy to the clipboard. How might I do this?
<html>
<head>
<meta name="Recommended Share Difficulty Calculator" content="[Share Dicciculty Calculator]" />
<title>Recommended Share Difficulty</title>
<script type="text/javascript">
function MathThing()
{
input = prompt("Enter your max KH/s.", "");
if (input==null || input=="")
{
return false;
}
share = 0.00000116414 ;
total = input * share;
alert(input + " * " + share + " = " + total);
}
</script>
</head>
<body>
Calculate
</body>
</html>
In order to manipulate the contents of a users clipboard you will need to utilize Flash. There is a great helper library called ZeroClipboard. I've set up a basic demo (that uses your JavaScript) that uses this JavaScript:
var client = new ZeroClipboard(
$("#copy"), {
moviePath: "http://zeroclipboard.org/javascripts/zc/ZeroClipboard_1.3.2.swf"
});
client.on('dataRequested', function (client, args) {
client.setText((function () {
input = prompt("Enter your max KH/s.", "");
if (input == null || input == "") {
return;
}
share = 0.00000116414;
total = input * share;
alert('"'+input + " * " + share + " = " + total+'" copied to your clipboard');
return input + " * " + share + " = " + total;
})());
});
This code follows the examples provided in the Zero Clipboard, the odd thing is it doesn't seem to work 100% of the time. I do most of my work on computers that don't have Flash so I don't know if this reliability is part of the library or my computer. Good luck.
Copying cross-browser is tricky.
Here is some super-simple code showing an input + button use case:
var el = document.getElementById('input-id');
var sub = document.getElementById('submit-id');
var calc = function(e){
var q = el.value;
var share = 0.00000116414;
if (q.length > 0){
var res = q * share;
alert(res);
}
};
sub.addEventListener('click', calc);
Fiddle: http://jsfiddle.net/G6T76/3/
You'll probably want to do a bit more validation on the input, though.

Categories

Resources