How to re-enable my once disabled button with javascript - 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;
}

Related

Forward and Back Buttons react where the Caret Position is

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

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>

Guessing Game in Javascript

What I'm trying to do is make a simple guessing game where the user can any the number without limit but will be graded at the end when the guessed the number correctly based on the number of their guesses. However, with my code when I enter a number and press the button to multiple times the hint changes from "Higher" to "Lower" even if the number is not changed also the message that should be displayed when the number is guessed correctly is not showing. Here's my code, I'm a beginner so there's bound to be errors in the code and any help is appreciated.
<fieldset>
<input type="number" id="guess" />
<button onClick="checknum();">Check Number</button>
</fieldset>
<fieldset>
<p>Your current status:</p>
<output id="status_output">You have yet to guess anything.</output>
</fieldset>
<script type="text/javascript">
function checknum(){
var randomNumber = Math.floor((Math.random() * 100) + 1);
var guessNumber = document.getElementById("guess").value;
//var guessNumber = parseInt(guess.value);
var statusOutput = document.getElementById('status_output');
var counter = 0;
var isguessed = false;
do {
counter = (counter + 1)
if (guessNumber < randomNumber) {
statusOutput.value = ("Higher");
}
else if (guessNumber > randomNumber) {
statusOutput.value = ("Lower");
}
else if (guessNumber = randomNumber) {
set (isguessed = true());
statusOutput.value = ("Correct" + mark());
}
}
while (isguessed = false);
}
function mark(){
if (counter < 10){
statusOutput.value("Excellent");
}
else if (counter > 10 && counter <20){
statusOutput.value("Okay");
}
else
statusOutput.value("Needs Practice");
}
</script>
In your while you are assigning false to the variable named isguessed.
You want to do while (isguessed === false) instead. This will check if isguessed is set to false
isguessed = false : assigns the varibles isguessed to false
isguessed === false : a boolean expression return true or false

Count on click button1 and recount if on click button2

I have two buttons and a counter, I have to reset counter every time I change the button. I don't know how to reset the counter.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
clickCount();
count=0;
}
button2.onclick = function(){
clickCount();
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Pass a parameter to your clickCount function with the button name, and check if it has changed.
var count = 0;
var lastButtonClicked = "";
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(buttonName){
if (buttonName === lastButtonClicked)
{
count++;
}
else
{
count = 1;
lastButtonClicked = buttonName;
}
display.innerHTML = count;
}
button1.onclick = function(){
clickCount("1");
}
button2.onclick = function(){
clickCount("2");
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Just add the extra parameter that determines which button the counter is from.
var isFirstButton = true;
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
if (!isFirstButton){
count = 0;
}
isFirstButton = true;
clickCount();
}
button2.onclick = function(){
if (isFirstButton){
count = 0;
}
isFirstButton = false;
clickCount();
}
I updated your original code, added a active button variable which is chosen from the event target, this way, it doesn't matter how many buttons you want to count, they will all be unique, and you don't need a variable for each one.
This is similar to [stephen.vakil] post, however with this code, you do not need to name the buttons, just use the DOM and event target to define the uniqueness.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
var activeTarget; // which target are we counting
function clickCount(e){
var e = e || window.event; // IE or other browser event
var target = e.target || e.srcElement; // target from different browsers
if(target != activeTarget) { // Is this the current target?
count = 0; // No, reset counter
activeTarget = target; // and make it the active target
}
count++; // No matter which target, incr counter
display.innerHTML = count; // and display result
}
button1.onclick = function(e) { // don't forget the event arg
clickCount(e); // and pass it to the count function
}
button2.onclick = function(e) { // same as above
clickCount(e);
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
The reference for the source event target onclick calling object

Targeting two separate elements with JavaScript

I have an spinner element made from two spans for + and - and an text input element in the middle that shows the quantity selected from the increase and decrease:
<div class="quantity-spinner">
<span class="input-number-decrement">–</span><input class="input-number" type="text" value="1" min="0" max="10"><span class="input-number-increment">+</
</div>
I have two instances of this element, but currently when increasing the quantity for one of the elements it also controls the other one.
My question is, how can I separate the two elements, so that they are controller independently.
Here is my JavaScript:
(function() {
window.inputNumber = function(el) {
var min = el.attr('min') || false;
var max = el.attr('max') || false;
var els = {};
els.dec = el.prev();
els.inc = el.next();
el.each(function() {
init($(this));
});
function init(el) {
els.dec.on('click', decrement);
els.inc.on('click', increment);
function decrement() {
var value = el[0].value;
value--;
if(!min || value >= min) {
el[0].value = value;
}
}
function increment() {
var value = el[0].value;
value++;
if(!max || value <= max) {
el[0].value = value++;
}
}
}
};
})();
inputNumber($('.input-number'));
Thank you in advance!
try replacing
els.dec.on('click', decrement);
els.inc.on('click', increment);
by
el.prev().on('click', decrement);
el.next().on('click', increment);
you bug comes from the fact that els.dec and els.inc contain
predecessors and successors for both counters

Categories

Resources