I have an Virtual keyboard with Javascript the keyboard is typing in two inputs after reached maxlength it is focusing to second input. my problem is when i want to type in first input i should clicked to first input to focus it than typing with keyboard numbers
My question is How i can typing using this keyboard without clicking inside input, the first input should start typing immediately after i clicked on the buttons numbers
const maxLength = 7;
const firstInput = document.querySelector("#pin");
const secondInput = document.querySelector("#key");
const changedEvent = new Event("change")
let activeInput;
firstInput.addEventListener("focus", (event) => {
activeInput = event.target;
});
firstInput.addEventListener("change", (event) => {
console.log("i'm changing!");
if (firstInput.value.length >= maxLength) {
activeInput = secondInput;
secondInput.focus();
}
});
secondInput.addEventListener("focus", (event) => {
activeInput = event.target;
});
function resetNumber() {
if (!activeInput) {
console.log("pin");
return;
}
activeInput.value = "";
}
function setNumber(number) {
if (!activeInput) {
console.log("pin");
return;
}
activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
// manually tell the input that it has changed, so that the event listener defined above gets called. this usually only will happen with actual keyboard input
activeInput.dispatchEvent(changedEvent);
}
<button onclick="resetNumber()">Reset</button>
<button onclick="setNumber(0)">0</button>
<button onclick="setNumber(1)">1</button>
<button onclick="setNumber(2)">2</button>
<button onclick="setNumber(3)">3</button>
<button onclick="setNumber(4)">4</button>
<button onclick="setNumber(5)">5</button>
<button onclick="setNumber(6)">6</button>
<button onclick="setNumber(7)">7</button>
<button onclick="setNumber(8)">8</button>
<button onclick="setNumber(9)">9</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />
<button id="reset" onclick="resetNumber()">Reset</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />
<script>
const maxLength = 7;
const firstInput = document.querySelector('#pin');
const secondInput = document.querySelector('#key');
const resetBtn = document.querySelector('#reset');
for (let i = 9; i >= 0; i--) {
const numBtn = document.createElement('button');
numBtn.className = 'number';
numBtn.innerText = i;
resetBtn.parentElement.insertBefore(numBtn, resetBtn.nextSibling);
}
const numberBtns = document.querySelectorAll('.number');
const resetNumber = () => {
firstInput.setAttribute('value', '');
secondInput.setAttribute('value', '');
};
const setVal = (e) => {
const num = parseInt(e.target.innerText, 10);
if (firstInput.value.length <= maxLength) return firstInput.setAttribute('value', firstInput.value + num);
secondInput.setAttribute('value', secondInput.value + num);
};
numberBtns.forEach((btn) => btn.addEventListener('click', setVal));
</script>
Related
I am a new learner and I am facing a problem. I want to create a simple messaging app and I want that if there is no text inside the input field then the button should be disabled. Help me out.
Here is the code:
let sendMessage = document.getElementById("sendMessage");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
if (val.value === "") {
sendMessage.disabled = true;
} else {
sendMessage.disabled = false;
}
});
<div id="messages"></div>
<input type="text" id="val" />
<button id="sendMessage">Send</button>
You should use input event to set disabled to false or true. Set disabled to true by default and after button was clicked.
let sendMessage = document.getElementById("sendMessage");
let input = document.getElementById("val");
sendMessage.addEventListener("click", () => {
let val = document.getElementById("val");
let p = document.createElement("p");
let pTxt = document.createTextNode(val.value);
p.appendChild(pTxt);
val.value = "";
let messages = document.getElementById("messages");
messages.appendChild(p);
sendMessage.disabled = true;
});
input.addEventListener("input", () => {
if(input.value.length > 0){
sendMessage.disabled = false;
} else {
sendMessage.disabled = true;
}
});
<body>
<div id="messages"></div>
<input type="text" id="val"/>
<button id="sendMessage" disabled>Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Simply create a disabled class for the button if you use custom button.
Then listen to the input change and toggle the class on button if the input have value.
With your code :
const button = document.getElementById('sendMessage');
const input = document.getElementById('message-input');
const messagesBox = document.getElementById('messages');
input.addEventListener('input', () => sendMessage.disabled = input.value === '');
button.addEventListener('click', () => {
let p = document.createElement('p');
let pTxt = document.createTextNode(input.value);
p.appendChild(pTxt);
messagesBox.appendChild(p);
});
<body>
<div id="messages"></div>
<input type="text" id="message-input" />
<button id="sendMessage" disabled >Send</button>
<script src="app.js" type="text/javascript"></script>
</body>
Set a keyup input handler for the input field and a click handler for the button. In the snippet event delegation is used.
document.addEventListener(`input`, handle);
document.addEventListener(`click`, handle);
function handle(evt) {
const isInput = evt.target.closest(`#val`);
const isBttn = evt.target.closest(`#sendMessage`);
if (isInput) {
document.querySelector(`#sendMessage`).disabled = !isInput.value.trim();
}
if (isBttn) {
isBttn.disabled = isBttn;
const inputField = document.querySelector(`#val`);
document.querySelector(`#messages`).insertAdjacentHTML(`beforeend`,
`<li>${inputField.value.trim()}</li>`);
inputField.value = ``;
inputField.focus();
}
}
<ul id="messages"></ul>
<input type="text" id="val" />
<button id="sendMessage" disabled>Send</button>
I need to get the value of a input to be displayed in real time but I need to show some default text if the Input is empty or only spaces, but I cant seem to get it to work
const [productName, setProductName] = useState("");
const defaultProductName = "Name";
const handleChange = (event) => {
setProductName(event.target.value);
const inputValue = event.target.value;
const inputId = document.getElementById("productNameInput").innerHTML;
if (event.target.value.length == 0) {
document.getElementById("productNameID").innerHTML = defaultProductName;
} else {
document.getElementById("productNameID").innerHTML = inputValue;
}
};
<div className="productName" id="productNameID">
{defaultProductName}
</div>
<form>
<input type="text" id="productNameInput" onChange={handleChange} />
</form>
you can try:
if(document.getElementByID("productNameInput").value == " " | document.getElementByID("productNameInput").value.length == 0){
console.log("Input is empty")
}
I want to make it so when the user clicks the checkbox , the player Two input goes disabled. My problem is that the input remains disabled in both cases, doesn't matter if checkbox is checked or not.
const Initialization = (function() {
p1 = '';
p2 = '';
const playerOne = document.querySelector('#player1')
const playerTwo = document.querySelector('#player2')
const checkAI = document.querySelector('#computer')
const startButton = document.querySelector('#start')
startButton.addEventListener('click', () => {
p1 = Player(playerOne.value)
p2 = Player(playerTwo.value)
})
if (checkAI.checked = true) {
playerTwo.disabled = true;
} else {
playerTwo.disabled = false;
}
return {
p1,
p2,
}
})();
<label>Computer: <input type="checkbox" id="computer"></label><br/>
<input type="text" id="player1"><br/>
<input type="text" id="player2"><br/>
<input type="button" id="start" value="Start" />
worked by adding an eventListener to the checkbox.
checkAI.addEventListener('click',()=>{
if(checkAI.checked){
playerTwo.disabled = true;
}else{
playerTwo.disabled = false;
}
})
If you want to react on checkbox change you need to add event listener on this input. For example onclick or onchange. Take care to use comparaison operator in your if test checkAI.checked === true. You can find a JSFiddle
Event on checkbox input
You need an event handler and to test equality using == or ===
Here is a simpler version
const Initialization = function() {
const Player = str => console.log(str);
const playerOne = document.querySelector('#player1')
const playerTwo = document.querySelector('#player2')
const checkAI = document.querySelector('#computer')
const startButton = document.querySelector('#start')
let p1 = '';
let p2 = '';
startButton.addEventListener('click', () => {
p1 = Player(playerOne.value)
p2 = Player(playerTwo.value || "computer")
});
checkAI.addEventListener('click', (e) => {
const chk = e.target.checked;
playerTwo.disabled = chk;
if (chk) playerTwo.value="";
})
};
Initialization()
<label>Computer: <input type="checkbox" id="computer"></label><br/>
<input type="text" id="player1"><br/>
<input type="text" id="player2"><br/>
<input type="button" id="start" value="Start" />
You can accomplish this reactiveness by listening for the change event on the checkbox element and updating the input state accordingly:
const Initialization = (function() {
p1 = '';
p2 = '';
const playerOne = document.querySelector('#player1')
const playerTwo = document.querySelector('#player2')
const checkAI = document.querySelector('#computer')
const startButton = document.querySelector('#start')
startButton.addEventListener('click', () => {
p1 = Player(playerOne.value)
p2 = Player(playerTwo.value)
})
// listen for change event on checkbox
checkAI.addEventListener('change', () => {
// set playerTwo input to current checkbox state
playerTwo.disabled = checkAI.checked
})
return {
p1,
p2,
}
})();
<label>Computer: <input type="checkbox" id="computer"></label><br/>
<input type="text" id="player1"><br/>
<input type="text" id="player2"><br/>
<input type="button" id="start" value="Start" />
So I am a newbie and I am just practice
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue() {
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
addBtn.addEventListener('click', addValue);
<form action="">
<input type="text" id="input-text">
<button id="add">add value</button>
</form>
<p>Data: <span id="output"></span></p>
my first lesson of JS is function and with .textcontent. So I wrote a code that will output the value/ number I entered on the input field after I click the add value button but somehow my code doesn't work.
DISCLAIMER> I HAVENT LEARN LOOPS< IF STATEMENTS OR WHATSOEVER I just want to practice my lesson.
You just need to e.preventDefault() to prevent the form from submission and reload the page. It is the default behavior, so you need to prevent this behavior.
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue(e) {
e.preventDefault();
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
addBtn.addEventListener("click", addValue);
<form action="">
<input type="text" id="input-text">
<button id="add">add value</button>
</form>
<p>Data: <span id="output"></span></p>
Like some other people already mentioned, it's the <form> that's being submitted.
I'd recommend removing the <form></form> since there no use for it now:
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue() {
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
addBtn.addEventListener('click', addValue);
<input type="text" id="input-text">
<button id="add">add value</button>
<p>Data: <span id="output"></span></p>
Small side-note:
function addValue() {
const enteredValue = getUserInput();
const displayValue = enteredValue;
displayOutput(displayValue);
}
Can be simplified to just:
function addValue() {
displayOutput(getUserInput());
);
const userInput = document.getElementById("input-text");
const addBtn = document.getElementById("add");
const output = document.getElementById("output");
function displayOutput(text) {
output.textContent = text;
}
function getUserInput() {
return userInput.value;
}
function addValue() {
displayOutput(getUserInput());
}
addBtn.addEventListener('click', addValue);
<input type="text" id="input-text">
<button id="add">add value</button>
<p>Data: <span id="output"></span></p>
I need this replacer to use it for many inputs with one selector. Now I use different selectors and same code with just selectors differ
var en = "qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?~&";
var ru = "йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё?";
var alphabet = {};
for (var i = 0; i < en.length; i++) {
alphabet[en[i]] = ru[i];
}
var InputReciever = document.getElementById("InputReciever");
InputReciever.addEventListener("input", function() {
InputReciever.innerHTML = toRussianStr(this.value);
});
function toRussianStr(str) {
return str.replace(/\S/g, function(match) {
return alphabet[match] || match;
});
}
<div class="form__option">
<input placeholder="Город получателя" id="InputReciever" onfocus="this.placeholder=''" onblur="this.placeholder='Город получателя'" onkeydown="InputReciever.value=toRussianStr(InputReciever.value)" onchange="InputReciever.value=toRussianStr(InputReciever.value)"
type="text" class="InputReciever field" autocomplete="off" />
</div>
You can pass this to the listener, and I would use input or keyup rather than keydown.
document.querySelectorAll('.InputReciever')
const toAlphabetMap = (from, to) => from.split('').reduce((acc, ch, i) =>
({ ...acc, [ch]: to.charAt(i) }), {});
const en = "qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?~&";
const ru = "йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё?";
const alphabet = toAlphabetMap(en, ru);
const toRussianStr = str => str.replace(/\S/g, match => alphabet[match] || match);
const handleInput = input => {
console.log(input);
input.value = toRussianStr(input.value)
};
<div class="form__option">
<input
type="text"
class="InputReciever field"
placeholder="Город получателя"
onfocus="this.placeholder=''"
onblur="this.placeholder='Город получателя'"
oninput="handleInput(this)"
onchange="handleInput(this)"
autocomplete="off" />
<input
type="text"
class="InputReciever field"
placeholder="Город получателя"
onfocus="this.placeholder=''"
onblur="this.placeholder='Город получателя'"
oninput="handleInput(this)"
onchange="handleInput(this)"
autocomplete="off" />
</div>
Just don't use document.getElementById. Use document.getElementsByTagName('input')
Change the code inside the input event listener from input.innerHTML to input.value.
Here's an answer explaining the differences.
Eg.
var en = "qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?~&";
var ru = "йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё?";
var alphabet = {};
for (var i = 0; i < en.length; i++) {
alphabet[en[i]] = ru[i];
}
var input = document.querySelector("input");
input.addEventListener("input", function() {
input.value = toRussianStr(input.value);
});
function toRussianStr(str) {
return str.replace(/\S/g, function(match) {
return alphabet[match] || match;
});
}
<input class="input" type="text" placeholder="Город получателя"
autocomplete="off"/>