How to add values from two buttons to single inputbox? - javascript

Assume that I have two buttons with the values 'abc' and 'efg' respectively, and an inputbox.
This is what I want to achieve :
When I click the button with the value 'abc' a single time, the value 'a' gets appended to the inputbox. If I press it two times immediately the value suddenly changes to 'b' instead of 'a', and when I do it three times it changes to 'c' instead of 'b'.
I should be able to type double 'a''s (or any of 'a', 'b', 'c') by waiting some time between button clicks on button 'abc'. For instance : I first click button 'abc', then 'a' gets into the inputbox, I wait for a short time and clicks one more time to get another 'a'.
I want the same functionality with all the buttons ('abc' and 'efg').
I have linked sample expected output image.
View this jsfiddle Code
<div ng-controller="MyCtrl">
<input type="text" ng-model="btnTxt[btnarr]">
<button ng-modle="btnarr" ng-Click="change()">abc</button>
</div>
Expected output:
Can anyone help me with this ?

I have tried one without using built-in timer functions, and checking it manually.
Solution at Pastebin : pastebin.com/vHF517FN
See if it's good enough for you. Btw, I didn't really refactor much, will do it if you are satisfied with this (I'm also new to js -_-).
EDIT
Refactored anyway.
Refactored Solution at Pastebin : pastebin.com/EnHz2EHK
EDIT 2
Added it to JSFiddle. However, I had to add everything to HTML part to make it work there, moving script to script part isn't working for me (wonder why).
Solution at JSFiddle
<script>
var prevClick = '!';
var prevClickTime;
var clicks = 0;
function buttonClick(letters) {
var input = document.getElementById("put");
var backLetterIndex = (clicks == 0) ? letters.length-1 : clicks - 1;
if(letters[backLetterIndex] == prevClick) {
var now = (new Date()).getTime();
if(now - prevClickTime < 500) {
var val = input.value;
input.value = val.slice(0, val.length - 1);
}
else
clicks = 0;
}
else
clicks = 0;
prevClickTime = (new Date()).getTime();
prevClick = letters[clicks];
clicks = (clicks + 1) % letters.length;
input.value = input.value + prevClick;
}
</script>
<input id="put" type="text"></input>
<button onClick="buttonClick('abc');">abc</button>
<button onClick="buttonClick('defg');">defg</button>

I get it, you want to do phone keyboard.
I am not sure what exactly is your question so here I wrote complete example
http://jsfiddle.net/daybda4h/5/
Bacically, I wrote click event listener with timer if click comes within 200ms after another click I count up.
clicks++;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
updateInput(clicks, evt.target);
clicks = 0;
}, timeout);
Then, when no more clicks are comming, I take the final number of clicks, take data attribute of a button that says what letters does it control, and take the letter number according to num of clicks.
to add value to input, you simply take input value and add the same value + some custom string.
function updateInput(cl, btn) {
var input = document.getElementById("test");
var letters = btn.getAttribute("data-letters").split("");
input.value = input.value + letters[cl-1];
}
Hope this resolves your problem :)

Related

HTML5 JavaScript, How can I clear my input field every time I hit the spacebar so there is only ever max 1 word showing in the input field?

I have 2 input fields where the second is a copy of the first using this code.
window.onload = function() {
var src = document.getElementById("paragraph-text"),
dst = document.getElementById("copy");
src.addEventListener('input', function() {
dst.value = src.value;
});
};
For every key I press when filling the first field, it shows up in the second filed. However, I'd like to have only 1 word show up at a time in the second (copy) field, meaning I want the field to clear every time I hit the spacebar (or keycode 32). Could someone help me out please.
It probably doesn't matter but here are the 2 html fields:
<input type="text" id="paragraph-text" name="paragraph-text" placeholder="type here to begin...">
<input type="text" id="copy" name="copy">
I tried this in the JavaScript:
window.onload = function() {
var src = document.getElementById("paragraph-text"),
dst = document.getElementById("copy");
src.addEventListener('input', function() {
dst.value = src.value;
window.onkeydown = function(event) {
if (event.keyCode == 32) {
src.value += ' '
dst.value = ''
if(event.preventDefault) event.preventDefault();
return false;
}
}
});
};
and it works except for the fact that when I type the next word, the original word is still there, so if i type a long sentence, the copy field will still contain all the words from the paragraph-text field, even though it does clear temporarily with every spacebar press. I would like it to stay cleared so the next word is alone, and so on. There should only ever be 1 word or nothing in the copy field.
I'm not a 100% sure I understand what you actually want, but I think this might be what you're after?
window.onload = function() {
var src = document.getElementById("paragraph-text"),
dst = document.getElementById("copy");
src.addEventListener('input', function() {
dst.value = src.value.split(' ').pop();
});
};
The first input might contain a word, or a sentence containing multiple words separated by whitespaces.
The second input should contain the last word from the first input.
We convert the contents of the first input to an array of words using split(' ') and then pop() to return the last item.

Multiple input and multiple output with onclick eventlistener in javascript

Want to ask :
For example , i have multiple button and when i click on anyone, the value will be shown at the result textbox and the input textbox will back to 0 , need help on check my code :
document.getElementById("plusthevalue").addEventListener('click',function plus()
{
var inputvalue = document.getElementById("Input");
var resultvalue = document.getElementById("Result");
document.write("Result").value = inputvalue + resultvalue;
document.write("Input").value ="0";
});
and, if i want to write a single statement that can include all the button and will display the output depend on the button, how would the code will be?
p/s: i know i can hardwork until i code function for every button but that would be very messy , i want to include all :(
You can assign all your buttons a certain class, then use document.querySelectorAll('.myclass') to grab all of them. Then you can loop through the results to add the event listener to each of them.
Example:
var myButtons = document.querySelectorAll('.myclass');
for (i = 0; i < myButtons.length; ++i) {
myButtons[i].addEventListener('click', function(e) {
// Do stuff
}
}
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for more info about querySelectorAll.

Increment and Decrement Javascript not working

i made a JavaScript function to increment and decrement a number in the like button, here is the function
var val = 0;
var negative = false;
$('.i-t').click(function(){
val = val + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});
This function works great on the first click but clicking the second time it doesn't remove the value, is something wrong with the function? here is the button
<button id="myvals" class="myvals">
<i class="myvals" id="i-t"></i>
<span class="myvals" id="voteScore">123</span></button>
i want to change the 123 to 124 if liked and 122 if disliked and it doesn't works, i'm sorry i had to prepare the question better from the beginning
From your comments and update, what you want to do is to increase/decrease the vote count based on whether you have already clicked or not.
In that case, instead of using a variable, you can store the state using a class to support multiple vote button if you need like
$('button.vote').click(function () {
var $btn = $(this).toggleClass('voted');
$(this).find("span.score").text(function (i, val) {
return +val + ($btn.hasClass('voted') ? 1 : -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="myvals vote"> <i class="myvals" id="i-t">here</i><span class="myvals score">123</span></button>
You need two buttons, one for up and one for down, or you could use one button and a checkbox for up or down, but I think two buttons is simpler.
When reading values from DOM elements, they're generally strings so if numbers are required, particularly for addition, don't forget to convert the value to a number before doing arithmetic.
So the buttons and code can be something like:
function vote(n) {
// Get the element to update
var el = document.getElementById('votes');
// Convert the text content to Number, then add value
el.textContent = Number(el.textContent) + n;
}
Votes: <span id="votes">123</span>
<button onclick="vote(1)">up vote</button>
<button onclick="vote(-1)">down vote</button>
Of course this is just a demo, adapt it however you wish.
Try this:
var val = 0;
var negative = false;
$('.i-t').click(function() {
val = parseInt($("#voteScore").val()) + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

jQuery submit form IF

Hey guys,
I have this great scripts someone on stack overflow helped me out with, except the one major function I need is missing.
This is a game where the user picks a number (by entering that number in a text field) then hits a play button. After they hit the play button a series of numbers will appear, they then have to click on the number that matches their number.
The query script I'm using counts how many times they hit the number and how many times they missed the number. Take a look at the script in action here. link text
now what I need it to do, is send the score (hits and misses ) to a database after 3 misses, so I can keep high score. Any ideas? Here's the script.
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
if (IsNumeric(n)) {
setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '');
}, <?php echo $time ?>);
}
$('#randomnumber').empty();
for (var i = 0; i < 5; i++) {
li.push($('<li />').click(function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
}
$this.addClass('clicked');
}).appendTo('#randomnumber'));
}
return false;
});
I've updated your problem here.
After updating the status Check for the missCount if it is greater than or equal to 3 then stop the play(clear the interval and unbind the event), then save the value using an ajax request.
I've changed the event handling to use event delegation instead of direct click event on the <li> elements. Event delegation is better in cases where there are lot of elements to which we have to bind a particular event.
I updated your fiddle with the solution. Check http://jsfiddle.net/DHPQT/2/.
I marked all the new stuff with a comment in the form of
//new ....
The main thing to do is checking after
$('#misscount').text(++missCount);
if missCount is 3 and if yes stop the game and send something

Categories

Resources