how to change element function with js - javascript

i have a <input type="text"/> which is to perform two functions. Which function is executed is to be decided via a button. This button should toggle the onkeyup function. For this I used the following:
document.getElementById('input-search-tags').onkeyup = filter_tagsC()
but when I click the button, the function will not change.

To toggle between which function fires onkeyup you need a click event listener on the button to set which function needs to be run.
const input = document.querySelector("input")
const button = document.querySelector("button")
let functionState = "one"
const oneFunc = () => console.log("one")
const twoFunc = () => console.log("two")
input.onkeyup = oneFunc
const toggleFunctions = () => {
if (functionState === "one") {
input.onkeyup = twoFunc
functionState = "two"
} else {
input.onkeyup = oneFunc
functionState = "one"
}
}
button.addEventListener("click", toggleFunctions)
<div>
<input type="text" />
<button>Toggle function</button
</div>
With this example, I get both elements with querySelector. Then I set a state value with let so that its value can be changed. Then I define the 2 functions I want to toggle between. I also set the input to have onkeyup of oneFunc, since the functionState starts as one.
Then I define a function that will assign a different function to onkeyup depending on the state of functionState and reset the functionState to the new value. Lastly, I add an event listener to the button to run the toggleFunctions function on click.

You need to specify that you are calling a function onKeyUp and then specify that function's name:
document.getElementById('input-search-tags').onkeyup = function() {filter_tagsC()}
function filter_tagsC() {
// Your Code Here.
}
For an an easier method of handling onkeyup, I would suggest looking at the keyup event listener method, as it is a bit more logical way of handling events. Hope this helps.

Related

How to get clicked button that was created dynamically?

I am trying to get a dynamically created button in order to access its parent.
I already tried to do:
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click(this)", add);
sadly the button won't work if i type "click(this)". It only works if I type "click".
Changing the method to function add(element) from function add() also did not work.
How can i access the parent of my clicked button?
I cant create my buttons in HTML since i am creating a dynamic list of buttons which may differ depending on the size of the array.
Also my code should only be in Javascript
Thanks for the help!
By magic, I mean by the standard, the button reference is passed to the object.
function add() {
console.log(this);
}
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click", add);
<div id="addButton"></div>
If you really wanted to pass along a variable
function add(btn, what) {
console.log(btn, what);
}
var btn = document.createElement("BUTTON");
btn.innerHTML="Add";
addButton.appendChild(btn);
btn.addEventListener("click", function(){ add(this,'foo'); });
<div id="addButton"></div>
Check this : https://www.w3schools.com/jsref/met_document_addeventlistener.asp
You should use btn.addEventListener("click", () => {}) instead of btn.addEventListener("click", () => {}).
But I think it would be better to use document.addEventListener((e) => {}) and then check the target (e.target)

Is it possible to have acces to innerHTML 'id' from otger part of the code?

I have following code, where, based on event, I add some html code. I would like to refer to 'id' from this dynamically injected html in other event (or just from other part of the code):
<div id="choice"></div>
var decisionList = document.getElementById("decisionList");
decisionList.addEventListener("change", function () {
var finalChoice = document.getElementById("choice");
finalChoice.innerHTML='<input id="finalDate" type="date">'
}
and other event referring to 'id' from innerHTML:
var payment = document.getElementById("finalDate");
payment.addEventListener("change", function () {
var textDate = payment.textContent;
alert(textDate);
})
The above is not working. Is it possible or not?
It is possible, but make that payment getter lazy. What that means is, instead of setting up that second change listener right away (in your other code), make that other code a function. Then in your first trigger, where you created the extra div or input or something, call that setup function.
decisionList.addEventListener("change", function () {
const finalChoice = document.getElementById("choice");
finalChoice.innerHTML='<input id="finalDate" type="date">'
createFinalDateListener();
}
function createFinalDateListener() {
const payment = document.getElementById("finalDate");
payment.addEventListener("change", function () {
const textDate = payment.textContent;
alert(textDate);
});
}
Here's a similar example. I do not have the input immediately. Or listener. And I only create a listener after I create the input.
// Here's the main trigger
function addExtraElements() {
// let's create a datepicker dynamically.
document.querySelector('#placeholder').innerHTML = '<input type="date" placeholder="pick date">';
listenDateChanges();
// TODO: don't forget to add cleanup code! Each time you fill that innerHTML, the old listener will remain
}
// Here's your datepicker listener
function listenDateChanges() {
const datePickerEl = document.querySelector('input[type="date"]');
if (!datePickerEl) {
console.log('no picker');
return;
}
datePickerEl.addEventListener('change', () => alert(datePickerEl.value));
}
<div id="placeholder">
Placeholder
</div>
<button onclick="addExtraElements()">Add extra elements</button>

How to get id of clicked button in winjs

I have several buttons in my WinJS page.
<button id="btn1">
Button 1
</button>
<button id="btn2"">
button 2
</button>...
and javascript to add click event to clicked button:
(function () {
WinJS.UI.processAll().done(function () {
var showButton = document.querySelector("xxx");
showButton.addEventListener("click", function () {
});
});
})();
How do i determine what button is clicked and set value of "xxx" to id of that button (btn1, btn2 etc...)
If I understood you correctly, you want to identify the button (sender) when you have multiple buttons that are attached to a single event handler.
MSDN:
In JavaScript, Windows Runtime event arguments are represented as a
single event object. In the following example of an event handler
method, the ev parameter is an object that contains both the sender
(the target property) and the other event arguments. The event
arguments are the ones that are documented for each event.
So you need to define an argument for the event handler and use its target property.
Let's say you have the following HTML:
<div id="label1"/>
<div>
<button id="button1">Button1</button><br />
<button id="button2">Button2</button><br />
<button id="button3">Button3</button><br />
</div>
and attached a single event handler to all of the buttons:
var button1 = document.getElementById("button1");
button1.addEventListener("click", buttonClickHandler);
var button2 = document.getElementById("button2");
button2.addEventListener("click", buttonClickHandler);
var button3 = document.getElementById("button3");
button3.addEventListener("click", buttonClickHandler);
you can access to sender in this way:
function buttonClickHandler(eventInfo) {
var clickedButton = eventInfo.target;
var label1 = document.getElementById("label1");
label1.innerHTML = clickedButton.id.toString();
}
Here's a WinJS solution to get the buttons :
var buttons = WinJS.Utilities.query('button');
Then you can bind the event to the buttons click :
buttons.forEach(function (btn) {
btn.addEventListener("click", function () {
console.log('button ' + this.id + ' has been clicked.');
})
});
I am new to WinJS, so there is probably a prettier solution to replace the forEach.
Something like this should work. querySelector only returns the first match, so you need to use querySelectorAll (see docs).
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
var id = this.id;
// do stuff with "id"
});
}
You might also consider looking into jQuery as that can make things like this a little bit cleaner.

Pure Javascript listen to input value change

Is there any way I can create a constant function that listens to an input, so when that input value changes, something is triggered immediately?
I am looking for something using pure javascript, no plugins, no frameworks and I can't edit the HTML.
Something, for example:
When I change the value in the input MyObject, this function runs.
Any help?
This is what events are for.
HTMLInputElementObject.addEventListener('input', function (evt) {
something(this.value);
});
As a basic example...
HTML:
<input type="text" name="Thing" value="" />
Script:
/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);
/* function */
function doThing(){
alert('Horray! Someone wrote "' + this.value + '"!');
}
Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/
Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:
HTMLInputElementObject.oninput = () => {
console.log('run'); // Do something
}
Or can be written like below:
HTMLInputElementObject.addEventListener('input', (evt) => {
console.log('run'); // Do something
});
Default usage
el.addEventListener('input', function () {
fn();
});
But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.
var event = new Event('input');
el.addEventListener('input', function () {
fn();
});
form.addEventListener('input', function () {
anotherFn();
});
el.value = 'something';
el.dispatchEvent(event);
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Another approach in 2021 could be using document.querySelector():
const myInput = document.querySelector('input[name="exampleInput"]');
myInput.addEventListener("change", (e) => {
// here we do something
});
This sounds exactly like the problem I had.
And I would have stated the same question, but I guess it's the same wrong question...
IMHO it's just 'onchange' mistaken as 'oninput' which are 2 different things.
Give me a lot of minus for this statement, I dont care, but I guess it may help one or the other ...
HTML form input contain many events. Refer from MDN document, on the sidebar go to Events menu and expand it. You will see many useful events such as beforeinput, change, copy, cut, input, paste, and drag drop events.
iput & change.
The beforeinput, and input events are fired by order when you type the form input value.
When the form input value has changed and you lost focus on that input, the change event is fired.
Cut, copy, paste.
When you cut (CTRL+X on keyboard shortcut) the input value, the cut, beforeinput, input events are fired.
When you copy (CTRL+C on keyboard shortcut), the copy event is fired alone.
When you paste the value from clipboard (CTRL+V on keyboard shortcut), the paste, beforeinput, input events are fired.
JS change value.
To change input value by JavaScript and make important events work, you need to dispatch at least 2 events by order. One is input and two is change. So that you can focus your code to listened to input or change event. It's easier this way.
Here is all sample code.
(() => {
let inputText = document.getElementById('text');
let submitBtn = document.getElementById('submit');
let triggerJSBtn = document.getElementById('button');
submitBtn.addEventListener('click', (event) => {
event.preventDefault(); // just prevent form submitted.
});
triggerJSBtn.addEventListener('click', (event) => {
const thisTarget = event.target;
event.preventDefault();
inputText.value = thisTarget.innerText;
inputText.dispatchEvent(new Event('input'));
inputText.dispatchEvent(new Event('change'));
});
inputText.addEventListener('beforeinput', (event) => {
const thisTarget = event.target;
console.log('beforeinput event. (%s)', thisTarget.value);
});
inputText.addEventListener('input', (event) => {
const thisTarget = event.target;
console.log('input event. (%s)', thisTarget.value);
});
inputText.addEventListener('change', (event) => {
const thisTarget = event.target;
console.log('change event. (%s)', thisTarget.value);
});
inputText.addEventListener('cut', (event) => {
const thisTarget = event.target;
console.log('cut event. (%s)', thisTarget.value);
});
inputText.addEventListener('copy', (event) => {
const thisTarget = event.target;
console.log('copy event. (%s)', thisTarget.value);
});
inputText.addEventListener('paste', (event) => {
const thisTarget = event.target;
console.log('paste event. (%s)', thisTarget.value);
});
})();
/* for beautification only */
code {
color: rgb(200, 140, 50);
}
small {
color: rgb(150, 150, 150);
}
<form id="form">
<p>
Text: <input id="text" type="text" name="text">
</p>
<p>
Text 2: <input id="text2" type="text" name="text2"><br>
<small>(For lost focus after modified first input text so the <code>change</code> event will be triggered.)</small>
</p>
<p>
<button id="submit" type="submit">
Submit
</button>
<button id="button" type="button">
Trigger JS to set input value.
</button>
</p>
<p>Press F12 to view results in your browser console.</p>
</form>
Please press F12 to open browser's console and see result there.
Each time a user inputs some value, do something.
var element = document.getElementById('input');
element.addEventListener('input', function() {
// Do something
});
Keydown, keyup, input are events that fire immediately when input changes,
I would use keydown or input events to get the changed value from the input box.
const myObject = document.getElementById('Your_element_id');
myObject.addEventListener('keydown', function (evt) {
// your code goes here
console.log(myObject.value);
});
If you would like to monitor the changes each time there is a keystroke on the keyboard.
const textarea = document.querySelector(`#string`)
textarea.addEventListener("keydown", (e) =>{
console.log('test')
})
instead of id use title to identify your element and write the code as below.
$(document).ready(()=>{
$("input[title='MyObject']").change(()=>{
console.log("Field has been changed...")
})
});

Select Tag Change Event Call on Selected Index Change

I have a select tag that has an eventListener on change.
Now I also have two different buttons that change it, that uses:
(selectTag).selectedIndex++;
The above does what I want to achieve, but it does not call my function callback on change.
How would I go about doing that? Other Approaches welcomed.
I would prefer pure-JS solutions, (noJquery please).
Just trigger change event when calling click handler on buttons:
var select = document.querySelector("select");
var button = document.querySelector("button")
select.addEventListener("change", function (e) {
alert(e.target.value)
});
button.addEventListener("click", function () {
var event;
try {
event = new Event("change")
} catch (e) {
event = document.createEvent("Event");
event.initEvent("change", true, false);
}
select.selectedIndex++;
select.dispatchEvent(event);
});
JS Bin
Update: I've changed it work in IE 10 and probably some others.

Categories

Resources