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

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.

Related

How to detect a button press with Gamepad API?

I am trying to write a web page where I can detect button presses on a Xbox controller and show a user a boolean value based on the button pressed. Right now, I can detect a controller being connected and show that as a string. The documentation says to use this code to detect a button press here:
var isPressed = navigator.getGamepads()[0].pressed;
but Chrome shows this error when using it:
Uncaught TypeError: Cannot read property 'pressed' of null
The error is linked to the .pressed part of the above line of code. All the documentation is on the Mozilla site, so I'm assuming they used FireFox when writing the tutorials.
What I ideally want to end up with is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<h id="button"></h>
<h id="gpInfo"></h>
<script>
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
});
var isPressed = navigator.getGamepads()[0].pressed;
document.getElementById("button").innerHTML = isPressed;
</script>
<!-- <script type="text/javascript" src="gamepadtest.js"></script> -->
</head>
</html>
The code would print a boolean value on the screen for users to see when they press a button.
This is my first time working with JavaScript and HTML. If you could make your answer noob-friendly that would be great! Documentation for Gamepad API and for GamepadButton
You shouldn't reference the Gamepad object until the gamepadconnected event has been thrown. Also, you'll need a loop to poll the button value. Here's some revised code:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});
I don't have enough reputation to just add a comment to Caleb Denio's answer, but regarding Nathan's comment on that answer:
I have used your example to listen for 20 buttons and i can detect each button, but once i have pressed one, it will not change another result for a different button.
I see the same behaviour on Chrome 90. Specifically, a new GamepadList instance, containing new Gamepad instances, all seem to be created each time the state of any gamepad changes (e.g. which of its buttons are pressed).
You can test it with this:
var gamepads = null;
function callback() {
var new_gamepads = navigator.getGamepads();
if(new_gamepads !== gamepads) {
console.log('New GamepadList!', new_gamepads);
gamepads = new_gamepads;
}
}
var interval = setInterval(callback, 100);
...for me, that logs 'New GamepadList!' each time I press/release a button.
Long story short, you need to poll navigator.getGamepads() each frame in order to detect changes in gamepad state.
A minimalist fix for Caleb Denio's answer would therefore be:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
// ===> Get a fresh GamepadList! <===
var gp = navigator.getGamepads()[e.gamepad.index];
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});

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

How do I write javascript cookies from a form and then print the info in an alert or hidden div?

How do I use JavaScript to write cookies from form fields, and then print the info in an alert or hidden div?
Here is an example of what I have tried thus far.....
<script type="text/javascript">
function cookieForm() {
document.cookie = "name_first" + encodeURIComponent(document.forms[0].name_first.value);
}
function printCustomerInfo() {
var queryData = decodeURIComponent(document.cookie);
var queryArray = queryData.split(";");
if (document.cookie) {
window.alert("Your info. is:" + queryArray[0]);
window.alert[0].name_last.value = QueryArray[1].substring(queryArray[1].lastIndexOf("=") + 1);
}
}
</script>
<input type="submit" value="Submit" onclick="cookieForm(), printCustomerInfo()"/>
First, you're missing the "=" in the cookie string:
document.cookie = "name_first=" + encodeURIComponent(document.forms[0].name_first.value);
Second, your queryData has no ";" to split by, and no last name value - at least from what you show here.
This I do not understand:
window.alert[0].name_last.value = ...
I would call a single function from your event, and let that parent both setting the cookie and parsing it. That way you can at least debug it better.
re: a div, you could do something like this:
document.getElementById("yourDiv").innerHTML = "Your info. is:" + queryArray[0];
document.getElementById("yourDiv").style.visibility = 'visible';
But in general it's better to use jquery for manipulating elements, because it mitigates browser differences, though it wouldn't matter in this case:
$("yourDiv").html("Your info. is:" + queryArray[0]);
$("yourDiv").css ( { 'visibility': 'visible' } );
Good luck.

Javascript code and methods do not work

I recently started learning javascrpt, but I have some experience with C#. My school gave me an old text book called Complete Concepts and Techniques(second Edition). this book was written by Shelly Cashman and Dorin Quasney... My problem is that I cant get any of the methods or functions to work. Here are 2 of my most current issues:
var scrollMsg = "Mortage rates are at their lowest!"
var msgSpace = "--- ---"
var beginPos = 0
function scrollingMsg() {
document.msgForm.scrollingMsg.value =
scrollMsg.substring(beginPos,scrollMsg.length)+msgSpace+scrollMsg.substring(0,begi
nPos)
beginPos = beginPos + 1
If (beginPos > scrollMsg.length) {
beginPos = 0
}
window.setTimeout("scrollingMsg()",200)
}
function doMort() {
document.MortCalc.Amount.value=" "
document.MortCalc.Rate.value=" "
document.MortCalc.Years.value=" "
document.MortCalc.Payment.value" "
document.MortCalc.Amount.focus()
}
The scrollingMsg() function does not work. It does not place anything in the scrollingMsg text box. So there is no message in it. My second issue is with the doMort() function. The function does clear any of the boxes nor does it set a focus. Can you please tell me what's wrong. P.S. These are not my own code. These were project codes from the txt book, but they do not work.
Try adding semicolons after each statement, and you have a typo ('If' needs to be lowercase).
I fixed the code to comply with JSLint, use this site to verify your javascript
http://www.javascriptlint.com/online_lint.php
var scrollMsg = "Mortage rates are at their lowest!";
var msgSpace = "--- ---";
var beginPos = 0;
function scrollingMsg() {
document.msgForm.scrollingMsg.value = scrollMsg.substring(beginPos,scrollMsg.length) + msgSpace + scrollMsg.substring(0,beginPos);
beginPos = beginPos + 1;
if (beginPos > scrollMsg.length) {
beginPos = 0;
}
window.setTimeout("scrollingMsg()",200);
}
function doMort() {
document.MortCalc.Amount.value=" ";
document.MortCalc.Rate.value=" ";
document.MortCalc.Years.value=" ";
document.MortCalc.Payment.value=" ";
document.MortCalc.Amount.focus();
}

Javascript functions. variable result. why undefined or doesn't if else statement function?

I need the values of the name, address, size, and topping fields to appear in a text box. Without problems the name and address appears correctly. However I can't seen to get the size function to work. It is a radio button, and thus I need only one size to appear. I haven't even tried an if else for the checkbox yet. Here is my code
<html>
<head>
<script>
function pizza() {
document.pizzaboy.comments.value = "Name:" + " " + pizzaboy.name.value + "\n" + "Address:" + " " + pizzaboy.address.value + "\n" + document.getElementById("small").value + document.getElementById("medium").value + document.getElementById("large").value + "\n" + pizzaboy.toppings.value;
{
var rslt = "";
if (document.pizzaboy.size[0].checked) {
rslt = rslt + "Size=Small\n";
} else if (document.pizzaboy.size[1].checked) {
rslt = rslt + "Size=Medium\n";
} else rslt = rslt + "Size=Large\n";
return rslt;
}
}
</head>
The second Javascript bracket might be throwing you an error, keeping your code from running correctly.
In this post, several (more general) ways to get values of radio buttons are explained:
Checking Value of Radio Button Group via JavaScript?
The first answer is using jQuery, but the following answers will help you i think.
You should try this. Answer here if you need further assistance.

Categories

Resources