Forward and Back Buttons react where the Caret Position is - javascript

Playing with the idea of a Keypad-Login.
I need to make Forward and Back Buttons.
The back and forward buttons seem to be getting the caret position.
The input is disabled and only button clicks are used.
How can I adjust the buttons A and B to not just type at the end of the value but place the letter where the caret position is?
function A(){ document.getElementById('user').value += "A"; }
function B(){ document.getElementById('user').value += "B"; }
function BackSpace(){document.getElementById('user').value=document.getElementById('user').value.substring(0,document.getElementById('user').value.length - 1);}
function Back(){
user.focus();
console.log(user.selectionStart-1);
if(user.selectionStart > 0 ){user.focus();
user.selectionEnd = user.selectionStart-1;
user.selectionStart = user.selectionStart;}}
function Forward(){
console.log(user.selectionStart);
user.focus();
user.selectionEnd = user.selectionStart+1;
user.selectionStart = user.selectionStart+1;}
<div>
<button type="button" id="userKeysIn">
<span class="">Username</span>
<input id="user" disabled="disabled" type="text" name="user">
</button>
</div>
<div>
<button type="button" onclick="A();">a</button>
<button type="button" onclick="B();">b</button>
<button type="button" onclick="BackSpace();">Backspace</button>
<button type="button" onclick="Back();">Back</button>
<button type="button" onclick="Forward();">Forward</button>
</div>
No JQuery Please.
And Thank You in Advance!

I used selectionStart and selectionEnd to check caret position
Here is something you are looking for
String.prototype.replaceBetween = function(start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};
function writeValue(value) {
var userInput = document.getElementById('user');
var inputValue = document.getElementById('user').value;
if (userInput.selectionStart === userInput.selectionEnd) {
inputValue = inputValue.substring(0, userInput.selectionStart) + value + inputValue.substring(userInput.selectionStart, inputValue.length);
} else {
inputValue = inputValue.replaceBetween(userInput.selectionStart, userInput.selectionEnd, value);
}
document.getElementById('user').value = inputValue;
}
function A(){
writeValue("A");
}
function B(){
writeValue("B");
}
See the codepen

Related

JavaScript-limited click count

I've got a problem with limited click counter using JavaScript. I have tried suggestions below but it seems like my problem might be somewhere else.
HTML/Javascript Button Click Counter
Basically I want to count clicks x times, which is provided from <input type="number"> field. It looks like the script is not recognizing this item in counting function.
Below I'd like to share example code:
function myFunction() {
var count = 0;
var number = document.getElementById("amount").value;
var btn = document.getElementById("clickme");
var disp = document.getElementById("clicked");
btn.onclick = function() {
count++;
disp.innerHTML = count;
}
if (count > number) {
btn.disabled = true;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" onclick="myFunction()">Click me</button>
<script>
</script>
</body>
</html>
Just remove the surrounding function and the onclick attribute.
Also, move the value retrieval and the disabled logic inside the listener, and convert the value to a number:
let count = 0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
const amount = document.getElementById("amount");
btn.onclick = function () {
count++;
disp.innerHTML = count;
const number = +amount.value;
if (count > number) {
btn.disabled = true;
}
}
<input type="number" id="amount" >
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme">Click me</button>
You can simply your solution using the snippet below.
let count = 0;
const inp = document.getElementById("amount");
const countEl = document.getElementById("clicked");
function myFunction(e) {
if (++count >= Number(inp.value)) e.target.disabled = true;
}
<input type="number" id="amount">
<p>How many times button should be clicked</p>
<p>Click the button.</p>
<button id="clickme" onclick="myFunction(event)">Click me</button>
I would recommend something like this. The limit can be increased or decreased at any time to allow for more or less clicks. Once it reaches 0, the button will stop adding to the count -
const f =
document.forms.myapp
function update (event) {
const limit = Number(f.limit.value)
if (limit <= 0) return
f.limit.value = limit - 1
f.count.value = Number(f.count.value) + 1
}
f.mybutton.addEventListener("click", update)
<form id="myapp">
<input type="number" name="limit" value="10">
<button type="button" name="mybutton">click me</button>
<output name="count">0</output>
</form>
I have managed to count the click events with the limit provided by <input type="number"> field and adding data to the array. Additioanlly, I am trying to decrease dynamically the amount of click events and remove last records from array using another button. Basically I have NAN value when I try to get counter value to decrease it.
It looks like this:
HTML code:
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p> Add question</p> <input type="text" id="question">
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" >add me</button>
<button id="delme">
delete me
</button>
</body>
</html>
JS code:
var count = 0;
var i=0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
var amount = document.getElementById("amount");
var question = document.getElementById("question");
var tab;
btn.onclick = function () {
count++;
disp.innerHTML = count;
var number = +amount.value;
tab=new Array(number);
tab[i]=question.value;
console.log(tab[i] + i);
question.value=" ";
i++;
if (count == number) {
btn.disabled = true;
}
}
var delbtn=document.getElementById("delme");
var countdown = parseInt(document.getElementById("clicked"));
delbtn.onclick = function () {
console.log(countdown);
countdown--;
disp.innerHTML = countdown;
if (countdown == 0) {
btn.disabled = true;
}
}

How to properly link basic calculator results to buttons? (failing to do so)

I'm new to javascript, this week was our second lesson that came with an assignment. Disclaimer: I have a learning disability so sorry ifgot the solution is really obvious.
Alright so in the first lesson we have to create a basic calculator with input fields, this went great, followed along with the teacher and thought I understood it. - Second lesson was making the calculator work with buttons instead.
This is what I came up with:
function insert(num) {
document.form.textview.value = document.form.textview.value + num
}
var result = document.getElementById('result');
result.addEventListener('click', function(number1, number2) {
var a = number1;
var b = number2;
var op = (document.querySelector("#operator").value);
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op == "min") {
calculate = a - b;
} else if (op == "divi") {
calculate = a / b;
} else if (op == "mul") {
calculate = a * b;
}
});
<form name="form">
<input type="text" name="textview">
</form>
<div id="operator">
<br>
<button onclick="insert(7)">7</button>
<button onclick="insert(8)">8</button>
<button onclick="insert(9)">9</button>
<button onclick="insert('/')" id="divi"> / </button>
<br>
<button onclick="insert(4)">4</button>
<button onclick="insert(5)">5</button>
<button onclick="insert(6)">6</button>
<button onclick="insert('*')" id="mul"> * </button>
<br>
<button onclick="insert(1)">1</button>
<button onclick="insert(2)">2</button>
<button onclick="insert(3)">3</button>
<button onclick="insert('-')" id="min"> - </button>
<br>
<button onclick="insert('C')"> C </button>
<button onclick="insert(0)"> 0 </button>
<button onclick="insert('')" id="result"> = </button>
<button onclick="insert('+')" id="add"> + </button>
</div>
Result: All buttons work and input the numbers but it seems to not connect with my function.
First I checked console log for errors but it doesn't give any. Then I asked my teachers and he said we're only allowed to use what we learned in the first 2 lessons, so i'm trying to stick with it but really have no clue what I did wrong here. Any help would be appreciated very muchthanks all!
Here is a sample code that can solve your problem. What is happening in this is.
Whenever you select anything from the keys check if its not a number using isNaN()
If its is not a number the add a space after and before it when inserting into the textbox
document.form.textview.value = document.form.textview.value + ' ' + num + ' ';
When the result button (=) is clicked get the value of the textbox
var operands = equation.split(' ');
Now you will have an array (operands) of 3 items which will have first item as the first number, second item as the operation and the third item as the second number.
Now you can operate accordingly. Below is a working snippet for the above solutions.
function insert(num) {
if (isNaN(num)) {
document.form.textview.value = document.form.textview.value + ' ' + num + ' '; // add a space after and before the operator
} else {
document.form.textview.value = document.form.textview.value + num;
}
}
var result = document.getElementById('result');
result.addEventListener('click', function() {
var equation = document.getElementById('equation').value;
var operands = equation.split(' '); // split the string by space which give you and array of 3 elements
var op = operands[1];
var a = operands[0];
var b = operands[2];
var calculate;
if (op == "+") {
calculate = a + b;
} else if (op == "-") {
calculate = a - b;
} else if (op == "/") {
calculate = a / b;
} else if (op == "*") {
calculate = a * b;
}
console.log('Result is: ' + calculate);
});
<form name="form">
<input type="text" id="equation" name="textview">
</form>
<div id="operator">
<br>
<button onclick="insert(7)">7</button>
<button onclick="insert(8)">8</button>
<button onclick="insert(9)">9</button>
<button onclick="insert('/')" id="divi"> / </button>
<br>
<button onclick="insert(4)">4</button>
<button onclick="insert(5)">5</button>
<button onclick="insert(6)">6</button>
<button onclick="insert('*')" id="mul"> * </button>
<br>
<button onclick="insert(1)">1</button>
<button onclick="insert(2)">2</button>
<button onclick="insert(3)">3</button>
<button onclick="insert('-')" id="min"> - </button>
<br>
<button onclick="insert('C')"> C </button>
<button onclick="insert(0)"> 0 </button>
<button onclick="insert('')" id="result"> = </button>
<button onclick="insert('+')" id="add"> + </button>
</div>
Read more about
.split()
isNaN()
There can be many more solutions to this using different ways. Try and explore. Good luck with your learning.
Hope this helps :)

Create button onclick function to act as arrow keys do

I have this Java script function that acts as a back space. This works fine but now I want to create a button that goes back, and one that goes forward without deleting the text ( like the behavior of your arrow keys ) . Any help with this is greatly appreciated.
function setBack() {
document.getElementById('user').value =
document.getElementById('user').value.substring(0,
document.getElementById('user').value.length - 1);
}
<input id="user" type="text">
<button type="button" onclick="setBack();">backspace</button>
<button type="button" onclick="">back</button>
<button type="button" onclick="">forward</button>
No jQuery please Native Javascript only.
Give this a try:
let input = document.getElementById('Test');
input.focus();
let index = 0;
document.getElementById('Prev').addEventListener('click', function(){
index -= 1;
if(index <= 0) {
index = input.value.length;
}
input.focus();
input.selectionEnd = index;
input.selectionStart = index;
});
document.getElementById('Next').addEventListener('click', function(){
console.log(index);
index += 1;
if(index > input.value.length) {
index = 0;
}
input.focus();
input.selectionEnd = index;
input.selectionStart = index;
});
<input id="Test" type="text" value="helloooo">
<button id="Prev">Prev</button>
<button id="Next">Next</button>
You can do that by obtaining the cursor location which is possible with selectionStart. Here is the sample code. You can add more features to this as per the requirement.
function back(){
console.log(user.selectionStart-1)
if(user.selectionStart !== 0 ){
user.focus();
user.selectionEnd = user.selectionStart
user.selectionStart = user.selectionStart-1
}
}
function forward(){
console.log(user.selectionStart)
user.focus()
user.selectionEnd = user.selectionStart+1
user.selectionStart = user.selectionStart+1
}
You can store caret position inside var say caretPosition . And pass caret position after back and forward. Just increment pos on forward and decrement pos on back. here is how i have tried.
var caretPosition = 0;
function updateLength(){
caretPosition = document.getElementById('user').value.length
}
function setBack(e) {
var str= document.getElementById('user').value;
var position =document.getElementById('user').selectionStart;
caretPosition = position-1;
document.getElementById('user').value =
str.substring(0,position - 1) + str.substring(position, str.length)
resetCaretPosition('user',caretPosition);
}
function back(){
caretPosition =(caretPosition>1)?caretPosition-1:caretPosition ;
resetCaretPosition('user',caretPosition);
}
function forward(){
caretPosition =caretPosition+1 ;
resetCaretPosition('user',caretPosition);
}
function resetCaretPosition(elemId, caretPos){
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
<input id="user" oninput="updateLength()" type="text">
<button type="button" onclick="setBack(event);">backspace</button>
<button type="button" onclick="back()">back</button>
<button type="button" onclick="forward()">forward</button>

How to re-enable my once disabled button with javascript

I've searched the questions here about 'how to enable my disabled button' but the one with the 'removeAttribute' simply does not work, don't know why.
I have this problem - once I reach 0 with my decrementing button it goes disabled so the user can't decrement to negative number but the problem is when I use the increment button the decrement one stays disabled, why ? I will be very greatfull if you guys tell me another way to solve this task. The point is I am now allowed to decrement below 0.
Here are my HTML and JS:
var value = 1;
var plus = document.getElementById('plus');
var minus = document.getElementById('minus');
function add() {
value++;
document.getElementById('num').innerHTML = value;
}
function take() {
value--;
document.getElementById('num').innerHTML = value;
if (value == 0) {
minus.disabled = true;
} else {
minus.disabled = false;
}
}
<input type="button" value="ADD" id="plus" onclick="add();">
<input type="button" value="TAKE" id="minus" onclick="take();">
<span id="num">1</span>
Because you do not run the logic when you click on the add button. You only do it on the minus button.
I would break it out into it own function
var value = 1;
var plus = document.getElementById('plus');
var minus = document.getElementById('minus');
function add() {
value++;
document.getElementById('num').innerHTML = value;
setBtnStates();
}
function take() {
value--;
document.getElementById('num').innerHTML = value;
setBtnStates();
}
function setBtnStates() {
if (value == 0) {
minus.disabled = true;
} else {
minus.disabled = false;
}
}
<input type="button" value="ADD" id="plus" onclick="add();">
<input type="button" value="TAKE" id="minus" onclick="take();">
<span id="num">1</span>
The statement can be simplified to
function setBtnStates() {
minus.disabled = value == 0;
}

function to increment / decrement more than stepper in javascript

Hello I am trying to rewrite a function that will increment / decrement more than 1 stepper in javascript. Here is what I tried so far
here is a codepen link http://codepen.io/Ongomobile/pen/XdyBgv/
Here is 1 of the steppers
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal("one",-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal("one",1)">+1</button>
</div>
// This is current one
function modify_qty(val) {
var qty = document.querySelector("#qty1").value;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.querySelector("#qty1").value = new_qty;
return new_qty;
}
This is what I tried
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
[name].value = new_qty;
return new_qty;
}
A few issues:
What's the purpose of this line parseInt(qty,10) + val;? parseInt is intended to convert a string into its equivalent digit. Not much point in calling it on a base10 number.
Not sure what the point of the name argument to stepperVal is. Isn't the amount to be stepped already implied by the value argument?
You can pass a reference to the object triggering the onclick event by passing this to your function declared within the onclick.
new_qty always evaluates to val
stepperVal(arg,-1) is actually the same as stepperVal(arg,0). Why not just call it that way?
Updated code
replace "one" with this in :
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal(this,-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal(this,1)">+1</button>
</div>
Simplified JS:
function stepperVal(event, val){
clicked_link = event.target
return clicked_link.value = Math.max(0, val); # Return the greater of 0 and `val`
}
Use following it must work:
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(document.getElementsByName(name),10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.getElementsByName(name).value = new_qty;
return new_qty;
}

Categories

Resources