I’m trying to remove an input field by clicking an “X button”. After it is removed it will not post its value when the form is submitted. A “+ button” appears that allows the user to add said input again. The input has an onclick event that opens a calendar and after reattaching, the calendar does not open on click anymore. I can’t use jQuery.
adderBtn.onclick = function (e) {
var elem = that.hiddenElems.shift();
that.collectionItemContainer.append(elem);
}
removerBtn.onclick = function (e) {
collectionItemElem.remove();
that.hiddenElems.push(collectionItemElem);
}
The question is how do I remove and reattach DOM nodes without losing the Events.
When you remove an element, as long as you keep a reference to it, you can put it back. So:
var input = /*...code to get the input element*/;
input.parentNode.removeChild(input); // Or on modern browsers: `input.remove();`
later if you want to put it back
someParentElement.appendChild(input);
Unlike jQuery, the DOM doesn't distinguish between "remove" and "detach" — the DOM operation is always the equivalent of "detach," meaning if you add the element back, it still has its handlers:
Live Example:
var input = document.querySelector("input[type=text]");
input.addEventListener("input", function() {
console.log("input event: " + this.value);
});
input.focus();
var parent = input.parentNode;
document.querySelector("input[type=button]").addEventListener("click", function() {
if (input.parentNode) {
// Remove it
parent.removeChild(input);
} else {
// Put it back
parent.appendChild(input);
}
});
<form>
<div>
Type in the input to see events from it
</div>
<label>
Input:
<input type="text">
</label>
<div>
<input type="button" value="Toggle Field">
</div>
</form>
If you remove the element without keeping any reference to it, it is eligible for garbage collection, as are any handlers attached to it (provided nothing else refers to them, and ignoring some historic IE bugs in that regard...).
To detach an element in function form:
function detatch(elem) {
return elem.parentElement.removeChild(elem);
}
This will return the 'detached' element
Hi I have a project using autosize text fields, these field need to be updated using an 'autosize:update' trigger if the field is edited by a script, but I'm having some trouble getting this to work. If I try entering:
$('.auto-size').trigger('autosize:update')
Into the console when the update needs to happen, nothing happens and I'm not sure why?
I'm pretty new to javascript/jquery so any help would be greatly appreciated.
As reported in the documentation you can use:
autosize.update($('.auto-size'));
or you can use:
var evt = document.createEvent('Event');
evt.initEvent('autosize:update', true, false);
$('.auto-size').get(0).dispatchEvent(evt);
An example:
// initialiaze the field
autosize($('.auto-size'));
// add new text to textarea and update!
$('#myBtn').on('click', function(e) {
var ele = $('.auto-size');
ele.text(ele.text() + 'This is a new line.\n');
autosize.update(ele);
// Dispatch a 'autosize:update' event to trigger a resize:
//var evt = document.createEvent('Event');
//evt.initEvent('autosize:update', true, false);
//$('.auto-size').get(0).dispatchEvent(evt);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"></script>
<textarea class="auto-size"></textarea>
<button id="myBtn">Click Me</button>
if autosize:update is a css property, it probably is but i can't find it online. But if it IS,
$(".auto-size").trigger(function(){
$(".auto-size").css("autosize","update");
});
I've found a dozen different SO articles on how to do this, but none of them are working.
I'm trying to write some tests, and I want to test that when I press enter in an input, the form does indeed post back. However, I can't get it to simulate this.
No matter which method I choose, the keypress event is being triggered--event listeners see it--but the form isn't being submitted.
jsFiddle link:
Html
<!-- returns an error on submit, but that's fine...
we're only seeing if we can get a submit to happen -->
<form action="POST">
<input id="myinput" type='text' value="foo" />
</form>
<div id="output"></div>
Javascript
$(function () {
var $input = $("#myinput");
$input.on("keypress", function (evt) {
$("#output").append("Typed: " + evt.keyCode + ", but the form didn't submit.<br>");
});
$("form").on("submit", function () { alert("The form submitted!"); } );
// try jQuery event
var e = $.Event("keypress", {
keyCode: 13
});
$input.trigger(e);
// try vanilla javascript
var input = $input[0];
e = new Event("keypress");
e.keyCode = 13;
e.target = input;
input.dispatchEvent(e);
e = document.createEvent("HTMLEvents");
e.initEvent("keypress", true, true);
e.keyCode = 13;
e.target = input;
input.dispatchEvent(e);
});
Is it possible to simulate an actual keypress like this?
If you focus on the text box (in jsFiddle) and physically press enter, the page will post back and will return something like:
This is what I'm trying to achieve, only in code.
Here's why:
$("input").on("keypress", function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
I ran into this in my code base, and I want to test that this sort of thing doesn't happen again.
To simulate the keypress event on the input we have to use the KeyboardEvent constructor and pass the event to the input's dispatchEvent method.
const event = new KeyboardEvent("keypress", {
view: window,
keyCode: 13,
bubbles: true,
cancelable: true
});
document.querySelector("input").dispatchEvent(event);
<!-- returns an error on submit, but that's fine...
we're only seeing if we can get a submit to happen -->
<form action="POST">
<input id="myinput" type='text' value="foo" />
</form>
<div id="output"></div>
You can see more information on mdn documentation on triggering and creating events
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...")
})
});
var check = function(){
return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
submit.onclick = check;
_submitSpan.appendChild(submit);
i created a form and append a input button, but i found it can't work in IE6, when click the button, the form auto submitted. can anybody help me.thank you.
Instead of explicitly setting the onclick attribute, try binding dynamically to the nodes' onclick event instead. Or perhaps you should be looking at the onsubmit event of the form.
function bindEvent(target, event, handler) {
if (typeof target.addEventListener != 'undefined') {
target.addEventListener(event, handler, false);
} else if (typeof target.attachEvent != 'undefined') {
target.attachEvent('on' + event, handler);
}
}
function check(e) {
// Cancel W3 DOM events
if (typeof e.preventDefault != 'undefined') {
e.preventDefault();
}
// Cancel for old IE event model
e.returnValue = false;
return false;
}
var submit = document.createElement("input");
submit.type = "image";
submit.src = "submit1.gif";
_submitSpan.appendChild(submit);
// Bind click event to submit button...
bindEvent(submit, 'click', check);
// ...or perhaps you want to bind submit event to form
bindEvent(submit.form, 'submit', check);
It might be an idea to hook into a 3rd party lib to handle event inconsistencies et al, YUI does a fine job, as does jquery.
For IE you might have to use the addAttribute method instead of .onclick()
submit.addAttribute('onclick', check);
From W3C HTML 4.01 Specs:
image
Creates a graphical submit button. The value of the src attribute specifies the URI of the >image that will decorate the button. For accessibility reasons, authors should provide >alternate text for the image via the alt attribute.
Do not use an <input type="image"> like a checkbox. The best way to make an image-checkbox is something like:
<label for="input">
<input id="input" style="display:none;" type="checkbox">
<img src="img.gif" alt="Check">
</label>
The label will treat the image as a checkbox, and automatically check the hidden checkbox if the image is clicked.