How to set input value using javascript program - javascript

Okay, so here is what I got here. I am using this site, [http://freedoge.co.in/#][1] with my auto-rolling bot. The bot I am using at the moment starts at the lowest value possible since there is already a button on the site for it. But, I want my bot to start at .05.
This is the input value that my bot needs to change before every roll...
<input id="double_your_doge_stake" type="text" style="text-align:center;" value="0.00000001" name="stake"></input>
And here is my bot script... it runs in the browser when the user uses inspect element and plays the program.
bconfig = {
maxBet: 28000,
wait: 200,
toggleHilo: false
};
hilo = 'lo';
multiplier = 4;
rollDice = function () {
if ($('#double_your_doge_bet_lose') .html() !== '') {
$('#double_your_doge_2x') .click();
multiplier++;
if (bconfig.toggleHilo) toggleHiLo();
} else {
$('#double_your_doge_min') .click();
multiplier = 2;
}
if (parseFloat($('#balance') .html()) < (parseFloat($('#double_your_doge_stake') .val()) * 2) ||
parseFloat($('#double_your_doge_stake') .val()) > bconfig.maxBet) {
$('#double_your_doge_min') .click();
}
$('#double_your_doge_bet_' + hilo + '_button') .click();
setTimeout(rollDice, (multiplier * bconfig.wait) + Math.round(Math.random() * 100));
};
toggleHiLo = function () {
if (hilo === 'lo') {
hilo = 'lo';
} else {
hilo = 'lo';
}
};
rollDice();

Use val.
$('#double_your_doge_stake').val(value)

Related

JS random order showing divs delay issue

I got function within JS which is supposed to show random order divs on btn click.
However once the btn is clicked user got to wait for initial 10 seconds ( which is set by: setInterval(showQuotes, 10000) ) for divs to start showing in random order which is not ideal for me.
JS:
var todo = null;
var div_number;
var used_numbers;
function showrandomdivsevery10seconds() {
div_number = 1;
used_numbers = new Array();
if (todo == null) {
todo = setInterval(showQuotes, 10000);
$('#stop-showing-divs').css("display", "block");
}
}
function showQuotes() {
used_numbers.splice(0, used_numbers.length);
$('.container').hide();
for (var inc = 0; inc < div_number; inc++) {
var random = get_random_number();
$('.container:eq(' + random + ')').show();
}
$('.container').delay(9500).fadeOut(2000);
}
function get_random_number() {
var number = randomFromTo(0, 100);
if ($.inArray(number, used_numbers) != -1) {
return get_random_number();
} else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
Question: How to alter the code so upon the btn click divs will start showing right away without initial waiting for 10 seconds? (take in mind I want to keep any further delay of 10 seconds in between of each div being shown)
Thank you.
Call it when you begin the interval
todo = setInterval((showQuotes(),showQuotes), 10000);

jQuery Placeholder Animation

I have an HTML Form that currently has an empty placeholder value.
TypingEffect() randomly selects one of eight examples and then calls type() to type them out as the placeholder. Then, after an interval of 2000, it applies an erasing effect that will erase it.
I think my problem lies within my syntax, more specifically the TypingEffect() function but I can't figure it out.
FIDDLE
HTML:
<form action="" method="get" type="search">
<input type="text" class="textbox" placeholder='' />
</form>
Javascript + jQuery:
$(document).ready(function() {
setInterval ('cursorAnimation', 600);
textbox = $('.textbox');
setInterval ('TypingEffect', 600);
setInterval ('ErasingEffect', 2000);
});
function TypingEffect() {
var tag = Math.floor((Math.random() * 10) + 1);
if (tag = 1) { caption = "Example1" }
if (tag = 2) { caption = "Example2" }
if (tag = 3) { caption = "Example3" }
if (tag = 4) { caption = "Example4" }
if (tag = 5) { caption = "Example5" }
if (tag = 6) { caption = "Example6" }
if (tag = 7) { caption = "Example7" }
if (tag = 8) { caption = "Example8" }
type();
}
function type() {
textbox.attr("placeholder", (caption.substr(0, captionLength++)));
if(captionLength < caption.length+1) {
setTimeout('type()', 50);
} else {
captionLength = 0;
caption = '';
}
}
function ErasingEffect() {
caption = captionEl.html();
captionLength = caption.length;
if (captionLength>0) {
erase();
}
}
function erase() {
textbox.attr("placeholder",(caption.substr(0, captionLength--)));
if(captionLength >= 0) {
setTimeout('erase()', 50);
} else {
captionLength = 0;
caption = '';
}
}
I updated your fiddle to make it work. https://jsfiddle.net/uxftux9w/5/
There were a few issues but I think some were from copying your code into jsfiddle, e.g. cursorAnimation variable and that you have not included jQuery in the fiddle
The main problems were the use of setInterval like Shilly pointed out. Use the function name rather than a string like so setInterval('type()', 50)
setInterval(type, 50)
The other problem was the fact that you were using two setInterval's as follows
setInterval ('TypingEffect', 600);
setInterval ('ErasingEffect', 2000);
These will just repeatedly call the two functions without taking into account the any differences in the length of the caption you are trying to type.
Instead I used setTimeout to delay the initial call to the TypingEffect and ErasingEffect functions, and setInterval to repeatedly call the type/erase functions until the caption is fully typed, or deleted. Here is the code. I added comments so I hope it some sense. There are quite a few ways you could optimise and reduce repetition if you want.
HTML
<form action="search.php" method="get" type="search">
<input type="text" class="textbox" placeholder='' />
</form>
JavaScript
$(document).ready(function() {
var textbox = $('.textbox'),
captionLength = 0,
caption = '',
id = setTimeout(TypingEffect, 600); //call onces and set an Id so it can be cleared
function TypingEffect() {
// console.log('TypingEffect');
var tag = Math.floor((Math.random() * 8) + 1);
if (tag == 1) {
caption = "Example1"
}
if (tag == 2) {
caption = "Example Example 2"
}
if (tag == 3) {
caption = "Example3"
}
if (tag == 4) {
caption = "Example Example 4"
}
if (tag == 5) {
caption = "Example5"
}
if (tag == 6) {
caption = "Example Example Example 6"
}
if (tag == 7) {
caption = "Example7"
}
if (tag == 8) {
caption = "Example Example 8"
}
clearTimeout(id); //clear first clearTimeout(TypingEffect, 600) call
captionLength = 1; //start at 0
id = setInterval(type, 50); //call type every 50ms
}
function type() {
// console.log('type', caption, caption.substring(0, captionLength++));
textbox.attr("placeholder", caption.substring(0, captionLength++));
//when finshed typing clear interval and call erase
if (captionLength === caption.length + 1) {
// console.log('end type');
clearInterval(id); //clear clearInterval(type, 50)
id = setTimeout(ErasingEffect, 1000); //start erase call once after delay
}
}
function ErasingEffect() {
// console.log('ErasingEffect');
clearTimeout(id); //clear clearTimeout(ErasingEffect, 2000); call
captionLength = caption.length; //start at end
id = setInterval(erase, 50); //call erase every 50ms
}
function erase() {
// console.log('erase');
textbox.attr("placeholder", caption.substring(0, captionLength--));
//when finshed erasing clear interval and call type
if (captionLength < 0) {
// console.log('end erase');
clearInterval(id); //clear clearInterval(erase, 50)
id = setTimeout(TypingEffect, 1000); //start over
}
}
});
Update - for those who prefer CSS
Here is a similar effect I discovered by Lea Verou done in pure CSS.

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

Can't Get Variable to Add Properly

I have a variable++; in an if/else statement (it being in the else part). It's supposed to add 1 to a score of how many wrong guesses one has.
For some reason it never adds just one, it will also add numbers ranging from 3 to 7 whenever I submit a 'guess'. Can you guys tell me if I'm looping wrong or something? Please try to explain in detail.
EDIT: I realized part of the problem. The tries++; is actually looping once for each letter [var]choice didn't match or equal. For instance if I enter "a" for "apple" tries++; will loop four times because of the four other characters. So how do I get it to only loop only once instead of adding one for each missed character?
This is my code.
// JavaScript Document
var words = new Array("apple","orange","banana","lime","mango","lemon","avacado","pineapple","kiwi","plum","watermelon","peach");
var randomNum;
var word;
var tries = 0;
$('#guess').prop('disabled', true);
$(function(){
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = "";
randomNum = Math.floor(Math.random() * words.length)
for (var i =0; i < words[randomNum].length; i++) {
word += "*";
}
console.log(words[randomNum]);
$('#word').html(word);
});
$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase();
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
}
if (words[randomNum].charAt(i) !== choice) {
tries++;
}
}
if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7)
$('#tries').html("YOU LOSE");
$('#word').html(word);
$('#' + choice).css("background-color", "red");
});
});
Got it working!
The issue is related to the tries variable, inside the for loop (per letter). In order to see the odd behavior add a console.log(tries); in your code, inside the loop and you will see. At first time it will increase in 1 then the value will change completely (I will suggest some debugging here to understand what's going on with more accuracy since I did this real quick). The solution is increasing the variable out of the for loop context to make it work (I did this in the provided example from the bottom).
By the way, it seems that you are trying to implement a "Hangman" game and to be honest, when implementing those things you need to be really organized.
I fixed your issue, improved the code a lot and also considered other possible game scenarios like:
Play Again
Game Over
Win
Go Back
Please take a look. Just to know, HTML and CSS are just improvisations made for this example, some improvements are needed so just take them as a reference.
Update: What you had put in the EDIT part from your post is correct.
You can run this script at the bottom.
// Game variables
var GAME_WORDS = [ // List of words available when playing
'apple',
'orange',
'banana',
'lime',
'mango',
'lemon',
'avacado',
'pineapple',
'kiwi',
'plum',
'watermelon',
'peach'
],
GAME_MASKED_WORD = '', // Stores the masked word to be discovered
GAME_SELECTED_WORD = '', // Stores the readable word
GAME_PLAYER_ATTEMPTS = 0, // Stores player attempts when failing
GAME_RANDOM_NUMBER = 0, // Random number to pick a word
GAME_MAX_ATTEMPTS = 7, // Max. player attempts before a game over
GAME_UI_COMPONENTS = { // UI components declaration
start: $('#start'),
reset: $('#reset'),
back: $('#back'),
guess: $('#guess'),
msg: $('#msg'),
word: $('#word'),
letter: $('#letter')
},
GAME_UI_SECTIONS = { // UI sections declaration
menu: $('#menu'),
game: $('#game')
};
$(function() {;
var ui = GAME_UI_COMPONENTS;
// Initialize game
init();
// Start button handler
ui.start.on('click', function(e) {
start();
});
// Guess button handler
ui.guess.on('click', function(e) {
guess();
});
// Play Again button handler
ui.reset.on('click', function(e) {
reset();
start();
});
// Go Back button handler
ui.back.on('click', function(e) {
init();
});
});
/**
* Used to initialize the game for first time
*/
function init() {
var sections = GAME_UI_SECTIONS;
sections.menu.show();
sections.game.hide();
reset();
};
/**
* Used to start the game
*/
function start() {
var ui = GAME_UI_COMPONENTS,
sections = GAME_UI_SECTIONS,
words = GAME_WORDS;
sections.menu.hide();
sections.game.show();
GAME_RANDOM_NUMBER = Math.floor(Math.random() * words.length);
for (var i = 0; i < words[GAME_RANDOM_NUMBER].length; ++i) {
GAME_MASKED_WORD += '*';
}
GAME_SELECTED_WORD = words[GAME_RANDOM_NUMBER];
ui.word.html(GAME_MASKED_WORD);
ui.letter.focus();
};
/**
* Guess button handler
*/
function guess() {
var ui = GAME_UI_COMPONENTS,
words = GAME_WORDS,
matches = false,
choice;
// Clean messages each time player do a guess
showMsg('');
if (ui.letter && ui.letter.val()) {
choice = $.trim(ui.letter.val().toLowerCase());
}
if (choice) {
for (var i = 0; i < GAME_MASKED_WORD.length; ++i) {
if (words[GAME_RANDOM_NUMBER].charAt(i) === choice) {
GAME_MASKED_WORD = GAME_MASKED_WORD.substr(0, i) + choice +
GAME_MASKED_WORD.substr(i + 1);
matches = true;
}
}
if (!matches) {
++GAME_PLAYER_ATTEMPTS;
}
} else {
showMsg('Please type a letter.');
}
// Show attempts left if more than zero
if (GAME_PLAYER_ATTEMPTS > 0) {
showMsg('You have ' +
(GAME_MAX_ATTEMPTS - GAME_PLAYER_ATTEMPTS) +
' attempt(s) left.');
}
// Check game status each time doing a guess
if (isGameOver()) {
lose();
} else if (isGameWin()) {
win();
} else {
ui.word.html(GAME_MASKED_WORD);
}
ui.letter.focus();
};
/**
* Used to set all game variables from the scratch
*/
function reset() {
var ui = GAME_UI_COMPONENTS;
GAME_MASKED_WORD = '';
GAME_PLAYER_ATTEMPTS = 0;
GAME_RANDOM_NUMBER = 0;
showMsg('');
ui.guess.show();
ui.letter.val('');
ui.word.html('');
};
/**
* Handler when player lose the game
*/
function lose() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Lose!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};
/**
* Handler when player win the game
*/
function win() {
var ui = GAME_UI_COMPONENTS;
showMsg('You Win!');
ui.word.html(GAME_SELECTED_WORD);
ui.guess.hide();
};
/**
* Use to print UI messages for the player
*/
function showMsg(msg) {
var ui = GAME_UI_COMPONENTS;
ui.msg.html(msg);
};
/**
* Check game status, if player is going to lose the game
* #returns Boolean
*/
function isGameOver() {
return (GAME_PLAYER_ATTEMPTS >= GAME_MAX_ATTEMPTS);
};
/**
* Check game status, if player is going to win the game
* #returns Boolean
*/
function isGameWin() {
return (GAME_MASKED_WORD === GAME_SELECTED_WORD);
};
.btn {
cursor: pointer;
}
span#msg {
color: red;
font-weight: bold;
}
.text {
font-size: 3em;
}
input#letter {
width: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="wrapper">
<div id="menu">
<span class="text">Hangman!</span>
<br><br>
<img src="http://img3.wikia.nocookie.net/__cb20130207191137/scribblenauts/images/0/01/Hangman.png" height="200" width="120"/>
<br><br>
<input type="button" class="btn" id="start" value="Start Game"/>
</div>
<div id="game">
<span id="msg"></span>
<br><br>
Letter: <input type="text" id="letter" value="" maxlength="1"/>
<br><br>
<input type="button" class="btn" id="guess" value="Guess"/>
<input type="button" class="btn" id="reset" value="Play Again"/>
<input type="button" class="btn" id="back" value="Go Back"/>
<br><br>
Word: <div id="word" class="text"></div>
</div>
</div>
Hope this helps.
try this one:
Modify guess click handler like this:
$('#guess').click(function guess(){
var choice = $('#letter').val().toLowerCase(),
found = false;
for (var i =0; i < word.length; i++) {
if (words[randomNum].charAt(i) == choice) {
word = word.substr(0, i) + choice + word.substr(i + 1);
found = true
}
}
if(!found){
tries++;
}
if (tries < 7) {
$('#tries').html(tries)
} else if (tries >= 7){
$('#tries').html("YOU LOSE");
}
$('#word').html(word);
$('#' + choice).css("background-color", "red");
});
Also on start reset the tries:
$('#start').click(function(){
$('#guess').prop('disabled', false);
word = ""; tries = 0;

jQuery "keyup" crashing page when checking 'Word Count'

I have a word counter running on a DIV and after typing in a few words, the page crashes. The browser continues to work (par scrolling) and no errors are showing in Chrome's console. Not sure where I'm going wrong...
It all started when I passed "wordCount(q);" in "keyup". I only passed it there as it would split-out "NaN" instead of a number to countdown from.
JS:
wordCount();
$('#group_3_1').click(function(){
var spliced = 200;
wordCount(spliced);
}) ;
$('#group_3_2').click(function(){
var spliced = 600;
wordCount(spliced);
}) ;
function wordCount(q) {
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0)
var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
$('.message1').keyup(function() {
wordCount(q);
});
try
{
if (new Number( word_count ) < 0) {
$(".word_count").attr("id","bad");
}
else {
$(".word_count").attr("id","good");
}
} catch (error)
{
//
}
};
HTML:
<input type="checkbox" name="entry.3.group" value="1/6" class="size1" id="group_3_1">
<input type="checkbox" name="entry.3.group" value="1/4" class="size1" id="group_3_2">
<div id="entry.8.single" class="message1" style="height: 400px; overflow-y:scroll; overflow-x:hidden;" contenteditable="true"> </div>
<span class="word_count" id="good"></span>
Thanks in advanced!
This is causing an infinite loop if (new Number(word_count) < 0) {.
Your code is a mess altogether. Just study and start with more basic concepts and start over. If you want to describe your project to me in a comment, I would be glad to show you a good, clean, readable approach.
Update:
Part of having a good architecture in your code is to keep different parts of your logic separate. No part of your code should know about or use anything that isn't directly relevant to it. Notice in my word counter that anything it does it immediately relevant to its word-counter-ness. Does a word counter care about what happens with the count? Nope. It just counts and sends the result away (wherever you tell it to, via the callback function). This isn't the only approach, but I just wanted to give you an idea of how to approach things more sensefully.
Live demo here (click).
/* what am I creating? A word counter.
* How do I want to use it?
* -Call a function, passing in an element and a callback function
* -Bind the word counter to that element
* -When the word count changes, pass the new count to the callback function
*/
window.onload = function() {
var countDiv = document.getElementById('count');
wordCounter.bind(countDiv, displayCount);
//you can pass in whatever function you want. I made one called displayCount, for example
};
var wordCounter = {
current : 0,
bind : function(elem, callback) {
this.ensureEditable(elem);
this.handleIfChanged(elem, callback);
var that = this;
elem.addEventListener('keyup', function(e) {
that.handleIfChanged(elem, callback);
});
},
handleIfChanged : function(elem, callback) {
var count = this.countWords(elem);
if (count !== this.current) {
this.current = count;
callback(count);
}
},
countWords : function(elem) {
var text = elem.textContent;
var words = text.match(/(\w+\b)/g);
return (words) ? words.length : 0;
},
ensureEditable : function(elem) {
if (
elem.getAttribute('contenteditable') !== 'true' &&
elem.nodeName !== 'TEXTAREA' &&
elem.nodeName !== 'INPUT'
) {
elem.setAttribute('contenteditable', true);
}
}
};
var display = document.getElementById('display');
function displayCount(count) {
//this function is called every time the word count changes
//do whatever you want...the word counter doesn't care.
display.textContent = 'Word count is: '+count;
}
I would do probably something like this
http://jsfiddle.net/6WW7Z/2/
var wordsLimit = 50;
$('#group_3_1').click(function () {
wordsLimit = 200;
wordCount();
});
$('#group_3_2').click(function () {
wordsLimit = 600;
wordCount();
});
$('.message1').keydown(function () {
wordCount();
});
function wordCount() {
var text = $('.message1').text(),
textLength = text.length,
wordsCount = 0,
wordsRemaining = wordsLimit;
if(textLength > 0) {
wordsCount = text.replace(/[^\w ]/g, '').split(/\s+/).length;
wordsRemaining = wordsRemaining - wordsCount;
}
$('.word_count')
.html(wordsRemaining + " words remaining...")
.attr('id', (parseInt(wordsRemaining) < 0 ? 'bad' : 'good'));
};
wordCount();
It's not perfect and complete but it may show you direction how to do this. You should use change event on checkboxes to change wordsLimit if checked/unchecked. For styling valid/invalid words remaining message use classes rather than ids.
I think you should use radio in place of checkboxes because you can limit 200 or 600 only at a time.
Try this like,
wordCount();
$('input[name="entry.3.group"]').click(function () {
wordCount();
$('.word_count').html($(this).data('val') + " words remaining...");
});
$('.message1').keyup(function () {
wordCount();
});
function wordCount() {
var q = $('input[name="entry.3.group"]:checked').data('val');
var content_text = $('.message1').text(),
char_count = content_text.length;
if (char_count != 0) var word_count = q - content_text.replace(/[^\w ]/g, "").split(/\s+/).length;
$('.word_count').html(word_count + " words remaining...");
try {
if (Number(word_count) < 0) {
$(".word_count").attr("id", "bad");
} else {
$(".word_count").attr("id", "good");
}
} catch (error) {
//
}
};
Also you can add if your span has bad id then key up should return false;
See Demo

Categories