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" />
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 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>
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'm trying to validate an input field. When i try to submit without filling in something, it gives me the error i made: please start your question with: will i ever. So i'm trying to check wether the text that the user types into the field, starts with: will i ever.
However, when i type a single (or more) random character(s), it just submits the form. I want it to check if the input starts with those fixed tree words, otherwise, no submission.
{
const handleSubmitForm = e => {
const $form = e.currentTarget;
if (!$form.checkValidity()) {
e.preventDefault();
const field = $form.querySelector('.question_field');
showValidationInfo(field);
//$form.querySelector('.error').innerHTML = 'Some errors occured';
} else {
console.log('Form is valid => submit form');
}
};
const showValidationInfo = field => {
console.log(field);
let message;
if (field.validity.valueMissing) {
message = 'Please fill in a question starting with: Will i ever';
}
if (field.validity.typeMismatch) {
message = 'Type not right';
}
if (field.validity.rangeOverflow) {
const max = field.getAttribute('max');
message = 'Too big, max ${max}';
}
if (field.validity.rangeUnderflow) {
const min = field.getAttribute('min');
message = 'Too small, min ${min}';
}
if (field.validity.tooShort) {
const min = field.getAttribute('minlength');
message = 'Too short, minimum length is ${min}';
}
if (field.validity.tooLong) {
const max = field.getAttribute('maxlength');
message = 'Too long, maximum length is ${max}';
}
if (!field.value.toLowerCase().startsWith("will i ever")) {
message = 'Start your question with: Will i ever';
}
if (message) {
field.parentElement.querySelector('.error').textContent =
message;
field.parentElement.querySelector('.error').style.color = "red";
}
};
const handeInputField = e => {
const $field = e.currentTarget;
if ($field.checkValidity()) {
$field.parentElement.querySelector('.error').textContent = '';
if ($field.form.checkValidity()) {
$field.form.querySelector('.error').innerHTML = '';
}
}
};
const handeBlurField = e => {
const $field = e.currentTarget;
showValidationInfo($field);
};
const addValidationListeners = fields => {
fields.forEach($field => {
$field.addEventListener('input', handeInputField);
$field.addEventListener('blur', handeBlurField);
});
};
const init = () => {
const $form = document.querySelector('form');
$form.noValidate = true;
$form.addEventListener('submit', handleSubmitForm);
const fields = $form.querySelectorAll('.input');
addValidationListeners(fields);
};
init();
}
<div class="name_wrapper">
<form autocomplete="off" class="form_question" action="answer.html">
<label class="name question" for="name">Ask me a question</label>
<div class="question_wrapper">
<p class="error">Start your question with: Will i ever...</p>
<input class="field question_field" type="text" name="question" placeholder="Will i ever..." value="" required>
</div>
<input id="button" class="answr-btn btn-question" type="submit" value="answer it!">
<input autocomplete="false" name="hidden" type="text" style="display:none;">
</form>
</div>
This line makes no sense:
const fields = $form.querySelectorAll('.input');
There are no HTML elements with class="input" in your form.
Did you mean $form.querySelectorAll('input')?
The problem is how you are handling the validation, the key is in this line if (!$form.checkValidity()) { this will not check if your string starts with Will i ever you have to do it manually before the if, here you have an alternative solution:
{
const handleSubmitForm = e => {
const $form = e.currentTarget;
const field = $form.querySelector('.question_field');
//here we validate the form manually
const message = showValidationInfo(field);
//if a message is found we show the error on the DOM, if is undefined we have no errors and we can submit the form
if (message) {
e.preventDefault();
$form.querySelector('.error').innerHTML = message;
$form.querySelector('.error').style.color = "red";
} else {
console.log('Form is valid => submit form');
}
};
const showValidationInfo = field => {
if (field.validity.valueMissing) {
return 'Please fill in a question starting with: Will i ever';
}
if (field.validity.typeMismatch) {
return 'Type not right';
}
if (field.validity.rangeOverflow) {
const max = field.getAttribute('max');
return 'Too big, max ${max}';
}
if (field.validity.rangeUnderflow) {
const min = field.getAttribute('min');
return 'Too small, min ${min}';
}
if (field.validity.tooShort) {
const min = field.getAttribute('minlength');
return 'Too short, minimum length is ${min}';
}
if (field.validity.tooLong) {
const max = field.getAttribute('maxlength');
return 'Too long, maximum length is ${max}';
}
if (!field.value.toLowerCase().startsWith("will i ever")) {
return 'Start your question with: Will i ever';
}
return undefined;
};
const handeInputField = e => {
const $field = e.currentTarget;
if ($field.checkValidity()) {
$field.parentElement.querySelector('.error').textContent = '';
if ($field.form.checkValidity()) {
$field.form.querySelector('.error').innerHTML = '';
}
}
};
const handeBlurField = e => {
const $field = e.currentTarget;
showValidationInfo($field);
};
const addValidationListeners = fields => {
fields.forEach($field => {
$field.addEventListener('input', handeInputField);
$field.addEventListener('blur', handeBlurField);
});
};
const init = () => {
const $form = document.querySelector('form');
$form.noValidate = true;
$form.addEventListener('submit', handleSubmitForm);
const fields = $form.querySelectorAll('.input');
addValidationListeners(fields);
};
init();
}
<div class="name_wrapper">
<form autocomplete="off" class="form_question" action="answer.html">
<label class="name question" for="name">Ask me a question</label>
<div class="question_wrapper">
<p class="error">Start your question with: Will i ever...</p>
<input class="field question_field" type="text" name="question" placeholder="Will i ever..." value="" required>
</div>
<input id="button" class="answr-btn btn-question" type="submit" value="answer it!">
<input autocomplete="false" name="hidden" type="text" style="display:none;">
</form>
You have uncommented backtick at occured `;
hello i was just wondering if there is anyway to get an input value to change / use it for the healLevel = 70% i give it a try but i'm new to this and fail.
(function() {
var checkbox1 = document.getElementById("cb1");
var checkbox2 = document.getElementById("cb2");
heal = document.getElementsByClassName('hud-shop-item')[10];
petHeal = document.getElementsByClassName('hud-shop-item')[11];
useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
up = new Event('mouseup');
healLevel = 70;
HEAL1 = function() {
if (checkbox1.checked) {
heal.attributes.class.value = 'hud-shop-item';
useHeal.dispatchEvent(up);
heal.click();
}
};
HEAL2 = function() {
if (checkbox2.checked) {
petHeal.attributes.class.value = 'hud-shop-item';
usePetHeal.dispatchEvent(up);
petHeal.click();
}
};
script = function(e) {
if (e.keyCode == 82) {
HEAL1();
HEAL2();
}
};
document.addEventListener('keydown', function(e) {
script(e);
});
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutationRecord) {
if (parseInt(mutations[0].target.style.width) < healLevel) {
HEAL1();
HEAL2();
}
});
});
observer.observe(healthBar, {
attributes: true,
attributeFilter: ['style']
});
})();
<input type="number" min="1" max="100" value="70">
this is what i have tried this but didn't seen to work any ideas why i failed ?
i tried using document.querySelector what am i doing wrong?
(function() {
var checkbox1 = document.getElementById("cb1");
var checkbox2 = document.getElementById("cb2");
var elem = document.querySelector('input[type="number"]');
heal = document.getElementsByClassName('hud-shop-item')[10];
petHeal = document.getElementsByClassName('hud-shop-item')[11];
useHeal = document.getElementsByClassName('hud-toolbar-item')[4];
usePetHeal = document.getElementsByClassName('hud-toolbar-item')[5];
healthBar = document.getElementsByClassName('hud-health-bar-inner')[0];
up = new Event('mouseup');
healLevel = elem.value;
<input type="number" min="1" max="100" value="70">
HTML
<input type="number" min="1" max="100" value="70" id="healRate" onchange="updateHealLevel()">
JS
var healLevel = document.getElementById("healRate").value;
function updateHealLevel(){
healLevel = document.getElementById("healRate").value;
}
EDIT
Updated so that a change to the input value will update the healLevel.
To have the value change with the input, you must simply add an onchange event on the HTML component so that when the user changes this input, it will run the code which will update the healLevel.