Register an event for changing html input value in javascript - javascript

Is it possible to register an event for changing html input value in javascript?
I mean I have an input. And when I type into it an event is registered, but when I update its (inputs) value through javascript the input event is not called. What is a workaround here?
For example, when you type into input the resulting text is updated, but when you clear the input using button (in other words through javascript) the input event is not registered.
html
<input id="inpt" oninput="updateText()" />
<div id="txtDiv">
resulting text
</div>
<button id="btn">
Click
</button>
js
const input = document.getElementById("inpt");
input.addEventListener('input', function() {
const resultingText = document.getElementById("txtDiv");
resultingText.innerHTML = input.value;
alet("called");
});
const btn = document.getElementById("btn");
btn.addEventListener('click', function() {
input.value = "";
});
fiddle.

I found out that if you separate the logic in the event listener into its own function, you could just call that function when the button is pressed.
const input = document.getElementById("inpt");
input.addEventListener('input', function() {
changeText();
});
const btn = document.getElementById("btn");
btn.addEventListener('click', function() {
input.value = "";
changeText();
});
function changeText() {
const resultingText = document.getElementById("txtDiv");
resultingText.innerHTML = input.value;
alert("called");
}
JS Fiddle: https://jsfiddle.net/joabysvt/1/

Related

Button Text not updating within eventListener

Button text is not updating when the event is triggered. This is a submit event but I've also tried a click event. I've also tested the code outside of the event listener and it works correctly. So the problem seems to be within the event listener.
Here is the code:
let addToCartForms = document.querySelectorAll(".bundle-builder--add-to-bundle-form");
addToCartForms.forEach((el)=>{
let btn = el.querySelector('.add-to-cart');
let btnText = btn.innerText;
el.addEventListener("submit",(e)=>{
btn.innerText = "added"
});
})
Both click and submit work. Maybe the form is submitted so you can't see the effect?
let addToCartForms = document.querySelectorAll(".bundle-builder--add-to-bundle-form");
addToCartForms.forEach((el) => {
let btn = el.querySelector('.add-to-cart');
let btnText = btn.innerText;
el.addEventListener("submit", (e) => {
btn.innerText = "added"
});
})
<form class="bundle-builder--add-to-bundle-form">
<button class="add-to-cart">click</button>
</form>
Maybe this jQuery solution could work.
$('body').on('submit', '.bundle-builder--add-to-bundle-form .add-to-cart', function(e){
(e).preventDefault();
(this).text('added');
setTimeout(function() {
(this).submit()},500)
})

Replacing input type word on button click

I have the following JS function which should change the word "hi" to "yo" on a button click if the user has input this. For example "hi, how are you today?" ==> "Yo, how are you today?"
function changeWord() {
let str = document.getElementById('inputBox').innerHTML;
document.getElementById('inputBox').innerHTML = str.replace("hi", "yo");;
}
The above doesn't work when I call changeWord(); on click, any ideas?
You should be targeting the value of the input rather than the HTML.
const input = document.querySelector('input');
const button = document.querySelector('button');
button.addEventListener('click', changeWord, false);
function changeWord() {
const str = input.value;
input.value = str.replace("hi", "yo");
}
<input type="text" />
<button>Click</button>
Use .value instead of .innerHTML, like this:
let str = document.getElementById('inputBox').value;
document.getElementById('inputBox').value = str.replace("hi", "yo");

How do I keep an input focused even when I click a button outside it

Let's say I have an input
<input type="text" id="inPut" autofocus>
and a button
<button id="btn">Some text</button>
I want that onblur, it loses focus (as it normally would), but when I click this button, nothing happens to the focus i.e it does not lose focus
You can use JS to focus the input on button click.
const btn = document.querySelector("#btn");
const inp = document.querySelector("#inp");
btn.addEventListener("click", () => {
inp.focus();
});
<input id="inp" type="text">
<button id="btn">Click</button>
If you don't want the input to focus on click if it is not already focused.
You can store input's focus information in a variable, toggle that variable on button's mouseover event (this would work because mouseover fires before click and mouseover doesn't make the button active)
const btn = document.querySelector("#btn");
const inp = document.querySelector("#inp");
let isInputFocused = false;
btn.addEventListener("mouseover", () => {
if (inp === document.activeElement) {
isInputFocused = true;
} else {
isInputFocused = false;
}
});
btn.addEventListener("click", () => {
if (isInputFocused) {
inp.focus()
}
});
<input id="inp" type="text">
<button id="btn">Click</button>

(Vanilla) JS: Checkbox "checked" returning unexpected results

Using the pen below you can see there are two elements, a button and a checkbox input.
When the button is clicked I would like to determine the status of checkbox (clicked/not-clicked).
Regardless of the visual check mark presence or not, the console always logs false. Why is this?
https://codepen.io/sterlingbutters/pen/ZEGGgvm
EDIT (code):
HTML:
<input id='stall' type="checkbox">
<button id='button'>Test
JS:
var stall = document.getElementById('stall').checked;
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall);
}
You have to reasign stall on button click.
So Using
button.onclick = function () {
var stall = document.getElementById('stall').checked
console.log(stall);
}
It works fine.
Try this instead: assign the element to the variable, and then inside your onclick function you get the checked property every time it runs.
If you just store the boolean value of checked in a variable, it will never update. Primitive types like booleans are always stored as simple values, not as auto-updating references back to the original property.
var stall = document.getElementById('stall');
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall.checked);
}
<input id='stall' type="checkbox">
<button id='button'>Test
Once you assigned "stall", it won't be re-assiged in "button.onclick". You must re-assign, such as
var button = document.getElementById('button');
button.onclick = function () {
var stall = document.getElementById('stall').checked;
console.log(stall);
}
or better
var stall = document.getElementById('stall');
var button = document.getElementById('button');
button.onclick = function () {
console.log(stall.checked);
}

favorite script with local storage don't work

I want to add data-id from a button in favorite list.
I tried few solution but the click action is never detected in console .
html code is
<button class="icon-plus-circle i-circled i-small addToCart" date-id="myId" data-name="myName"></button>
js code is
button.addEventListener('click', function (){
var id = $(this).attr('data-id');
var name = $(this).attr('data-name');
console.log(id);
let Fav = {
id : id ,
name : name
};
let liste_json = JSON.stringify(Fav);
localStorage.setItem('listeFavoris', JSON.stringify(liste_json));
} )
You need to select the button
const button = document.querySelector('button');
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('click detected');
});
<button>Click Me</button>
PS - You have added click listener using javascript and have jQuery code inside. Don't mix up two, stick with one.

Categories