Why wouldn't onChange function of an input be activated when the value of the input is changed by javascript? For example why when clicking on the button alert wouldn't happen?
<html>
<body>
<input type="text" id="myInput" onchange="alert(1)" />
<button onclick = "document.getElementById('myInput').value = 'ads'">click</button>
</body>
</html>
How can I make the onchange function work then?
edit:
I now understand event won't be triggered automatically, how can I call it(jquery too) ?
Scripted value changes don't trigger an event. You have to manually trigger an event.
jQuery: $('#myInput').trigger('change');
Add the following code to the onchange event:
var input = document.getElementById("myInput");
if(input.fireEvent) input.fireEvent("onchange");
else {
var ev = document.createEvent('HTMLEvents');
ev.initEvent("change", true, false);
input.dispatchEvent(ev);
}
So, combined with your code (you should actually separate the JS code from the HTML):
<button onclick="var input = document.getElementById('myInput');input.value = 'ads';if(input.fireEvent)input.fireEvent('onchange');else{var ev=document.createEvent('HTMLEvents');ev.initEvent('change',true,false);input.dispatchEvent(ev);}">click</button>
Related
If I click a button the activeElement is the button.
If I leave an input box the activeElement is the Window.
If I leave an input box by clicking on a button the activeElement is ... both?
Why does the onfocusout event not register the same activeElement as the button?
Is there anyway I can access the click-on-button event from the function call of the inputbox-leave-event? ie can I ask, "Did you leave me for the lousy button?"
<button type="button" onclick = "myFunction()"> button </button><br>
<input type="text" onfocusout= "myFunction()"> </input>
<script>
function myFunction() {
console.log(document.activeElement);
}
</script>
You can add an event listener for the button inside the myFunction()
function myFunction() {
// console.log(document.activeElement);
var btn = document.getElementById("btn");
btn.addEventListener("click", function (event) {
console.log(event);
});
}
<!DOCTYPE html>
<html>
<body>
<button id="btn" type="button">button</button><br>
<input type="text" onfocusout="myFunction()" />
</body>
</html>
The activeElement read-only property of the Document interface returns the Element within the DOM that currently has focus.
Often activeElement will return a HTMLInputElement or HTMLTextAreaElement object if it has the text selection at the time. If so, you can get more detail by using the object's selectionStart and selectionEnd properties.
In addition, it is indeed possible to trigger a button click when leaving the input element, you just need to make sure to handle the onfocusout function, and use the code inside the function to trigger the click event, you can refer to here.
function onMouseUp(e) {
const activeTextarea = document.activeElement;
const selection = activeTextarea.value.substring(
activeTextarea.selectionStart, activeTextarea.selectionEnd
);
const outputElement = document.getElementById('output-element');
const outputText = document.getElementById('output-text');
console.log({ id: activeTextarea.id, selection});
}
const textarea1 = document.getElementById('textarea1');
const textarea2 = document.getElementById('textarea2');
textarea1.addEventListener('mouseup', onMouseUp, false);
textarea2.addEventListener('mouseup', onMouseUp, false);
<textarea name="textarea1" id="textarea1" rows="7" cols="40">This is Text Area One.</textarea>
<textarea name="textarea2" id="textarea2" rows="7" cols="40">This is Text Area Two</textarea>
The relatedTarget in the event will show you where it's leaving to
of course, you have to use addEventListener to access the event in the first place
But I think this demonstrates what you want to see
it'll definitely tell you
"Did you leave me for the lousy button?"
const button = document.querySelector('button')
const input = document.querySelector('input')
function buttonHandler(e) {
console.log('button clicked');
}
function inputHandler(e) {
console.log('leaving input for', e.relatedTarget?.tagName || 'window');
}
input.addEventListener('focusout', inputHandler);
button.addEventListener('click', buttonHandler);
<button type="button"> button </button><br>
<input type="text"> </input>
I have the following code:
myInput.change(function (e) { // this triggers first
triggerProcess();
});
myButton.click(function (e) { // this triggers second
triggerProcess();
});
The problem with the above is when I click myButton both events are triggered and triggerProcess() is fired twice which is not desired.
I only need triggerProcess() to fire once. How can I do that?
Small demo
You can have a static flag that disables any more triggers once the first trigger has occurred. Might look something like this:
var hasTriggered = false;
myInput.change(function (e) { // this triggers first
triggerProcess();
});
myButton.click(function (e) { // this triggers second
triggerProcess();
});
function triggerProcess () {
// If this process has already been triggered,
// don't execute the function
if (hasTriggered) return;
// Set the flag to signal that we've already triggered
hasTriggered = true;
// ...
}
For resetting the hasTriggered flag, that's entirely up to you and how this program works. Maybe after a certain event occurring in the program you'd want to reenable the ability to trigger this event again — all you'd need to do it set the hasTriggered flag back to true.
You can use the mousedown event, which will fire before the input is blurred, and then check if the input has focus by checking if it's the activeElement, and if it does have focus, don't fire the mousedown event, as the change event will fire instead.
Additionally, if you want a mousedown event to occur when the value hasn't changed, and the change event doesn't fire, you'll need a check for that as well
var myInput = $('#test1'),
myButton = $('#test2'),
i = 0;
myInput.change(function(e) { // this triggers first
$(this).data('prev', this.value);
triggerProcess();
});
myButton.mousedown(function(e) { // this triggers second
var inp = myInput.get(0);
if (document.activeElement !== inp || inp.value === myInput.data('prev'))
triggerProcess();
});
function triggerProcess() {
console.log('triggered : ' + (++i))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test1">
<br />
<br />
<button id="test2">
Click
</button>
In a fairly typical scenario where you have an input with a button next to ie, eg quick search.
You want to fire when the input changes (ie onblur) but also if the user clicks the button.
In the case where the user changes the input then clicks the button without changing input focus (ie no blur), the change event fires because the text has changed and the click event fires because the button has been clicked.
One option is to debounce the desired event handler.
You can use a plugin or a simple setTimeout/clearTimeout, eg:
$('#inp').change(debounceProcess)
$('#btn').click(debounceProcess);
function debounceProcess() {
if (debounceProcess.timeout != null)
clearTimeout(debounceProcess.timeout);
debounceProcess.timeout = setTimeout(triggerProcess, 100)
}
function triggerProcess() {
console.log('process')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="inp">
<button id="btn">Click</button>
Use a real <button>BUTTON</button>. If you click on input text, alert is triggered, then once you leave the input text to click anywhere else, that unfocuses the input text which triggers the change event, so now 2 events have been triggered from the text input.
This is an assumption since the code provided is far from sufficient to give a complete and accurate answer. The HTML is needed as well as more jQuery/JavaScript. What is myInput and myButton actually referring to, etc.?
So I bet if you change...
var myButton = $('{whatever this is}'); and <input type='button'>
...TO:
var myButton = $("button"); and <button></button>
...you should no longer have an event trigger twice for an element.
This is assuming that triggerProcess() is a function that does something that doesn't manipulate the event chain or anything else involving events. This is an entirely different ballgame if instead of click() and change() methods you are using .trigger() or triggerHandler(), but it isn't. I'm not certain why such complex answers are derived from a question with very little info...?
BTW, if myInput is a search box and myButton is the button for myInput, as freedomn-m has mentioned, simply remove:
myButton.click(...
Leave myButton as a dummy. The change event is sufficient in that circumstance.
SNIPPET
var xInput = $('input');
var xButton = $('button'); //«———Add
xInput.on('change', alarm);
xInput.on('click', alarm);
xButton.on('click', alarm);
function alarm() {
return alert('Activated')
}
/* For demo it's not required */
[type='text'] {
width: 5ex;
}
b {
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1' name='f1'>
<input type='text'>
<input type='button' value='BUTTON TYPE'>
<label><b>⇦</b>Remove this button</label>
<button>BUTTON TAG</button>
<label><b>⇦</b>Replace it with this button</label>
</form>
While working on basic angular examples ng-click is not working as expected
the following is my html code :
<form ng-submit="requestFunding()" ng-controller="StartUpCalculator">
Starting :
<input ng-change='ComputeNeeded()' ng-model='funding.StartingEstimate'>Recommedation : {{needed}}
<button>Fund me</button>
<button ng-click="reset()">Reset</button>
</form>
Javascript code :
function StartUpCalculator($scope)
{
$scope.funding = {
StartingEstimate: 0
};
ComputeNeeded = function ()
{
$scope.needed = $scope.funding.StartingEstimate * 10;
};
$scope.requestFunding = function ()
{
window.alert("Whoa!");
};
}
whenever i click Reset(reset()) button it executes requestFunding function
Thre is no $scope.reset() in controller. You are triggering the ng-submit by clciking the button.
You can change <button> to <button type="button"> so it won't be bound to form submit. By default any button in a form with no type, and no click handler to preventDefault(), will trigger submit, however type="button" will not.
You also need to change ComputeNeeded to $scope.ComputeNeeded if you want it to work with ng-change
Because on ng-submit you are calling requestFunding. Add a new button and call requestFunding from there or else remove reset from form tag and place it putside.
I am trying to simulate a Keyboard event with jquery. What I want is when I click a button, I want a character to appear in a textarea. I need the action to be a keyboard simulation not a simple append. I have tried all the possible solutions on the web without any success, so I would be grateful if anyone can help me.
Here is my HTML/JS/Jquery code :
<html>
<head></head>
<body>
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<input type='text' id="input"></input>
<script type='text/javascript'>
function simulateKeyPress() {
document.getElementById("text").focus();
var e = $.Event("keypress");
e.which = 97;
$("input").trigger(e);
}
</script>
<br/>
<button id="button" onclick='simulateKeyPress()'>Press Me</button>
</body>
</html>
As you can see, when the button is clicked, I only get a focus on the text element, but no character appears, any ideas?
looks like I was not clear enough. Here is another sample, I am using the MouseTrap library to capture keyboard events.
Here is my code.
<html>
<header>
<title>test</title>
</header>
<script type='text/javascript' src='MouseTrap.js'></script>
<script type='text/javascript' src='jquery-1.9.1.min.js'></script>
<body>
<input type='text' class="mousetrap" id="input"></input>
<script type='text/javascript'>
Mousetrap.bind('4', function(){alert("you pressed 4" );});
function simulateKeyPress(character) {
document.getElementById("input").focus();
var input = $('#input');
input.val(input.val() + character);
}
</script>
<br/>
<button type="button" onclick='simulateKeyPress(4)'>Press Me</button>
</body>
</html>
With this code, whenever you press '4' on the keyboard, an alert box will appear. All I want is when I click the button, the same event to be created. Ideas?
Here is one solution to simulate the keypress :
var input = $('#input');
$('#button').click(function(){
// Add a character to the input
input.val(input.val() + 'x');
// Trigger the keypress event
input.keypress();
});
// Check if it work
input.on('keypress', function(){
alert('key pressed!');
});
Here is a jsfiddle demo.
Javascript does not perform default actions when you fire it from javascript. So the only way is to create your own vent handler :
function simulateKeyPress() {
document.getElementById("text").focus();
var e = $.Event("keypress");
e.which = 97;
$("input").trigger(e);
}
$("input").on('keypress', function(e){
//append e.which to your input here
});
It doesn't seem possible to acheieve this without appending the characters manually to the textarea.
The answers that #HighKickX and #claustrofob wrote only triggers the event handler as if the specificed key was pressed, but not actually presses that key like happens when a key is pressed on the keyboard (probably due to security reasons).
Because only the event is fired but the key is not actually pressed the textarea won't have that character added automatically.
try this
<input id="field">
<button id="x" class="button">submit</button>
$(".button").click(function() {
var value = $("#field").val();
$("#field").val( $("#field").val() + value);
});
I want to trigger an event hen the value of an input element using javascript.The value of the input element is changed using script ,and is not typed.I know that the onChange event fires not after the value is changed ,but after the value is changed and element looses focus(mouse is clicked outside the element.)..Here the input element does not loose focus.So onChange event willnot fire.So how to do that..
The following is the script ,once i tried and failed
<html>
<head>
<script type = 'text/javascript'>
function changed()
{
alert('changed');
}
function change()
{
document.getElementById('myId').value = 'Hello';
}
</script>
</head>
<body>
<input type = 'text' id = 'myId' onChange= 'javascript:changed();'/>
<input type ='button' value = 'change' onClick = 'javascript:change();'/>
</body>
I mean ,the function changed() should be called when the content inside textbox is changed using the function change().How to do that.
Here is the jsfiddle for the code http://jsfiddle.net/BFz2a/
Call changed() after change(): http://jsfiddle.net/BFz2a/11/
function change() {
document.getElementById('myId').value = 'Hello';
changed(); // Calls the other function
}
Contents inside event listeners (onchange=" this is inside ") is parsed as JavaScript. So, javascript: is obsolete. In fact, it is treated as a label.
The javascript:... prefix is only meaningful in links, eg Test.
The answer is simple
function change(){
var el = document.getElementById('myId');
el.value = 'Hello';
el.onchange(); // or simply call changed();
}
and javascript: is not needed inside onclick and onchange simply use
onClick = "change();"
In your function that handles the click event you could manually call the onchange event for the Input.
function change()
{
var inputEl = document.getElementById("myId");
inputEl.value = 'Hello';
inputEl.onchange();
}
function change(){
var el=document.getElementById('myId');
el.value="Something";
changed(el);
}
function changed(el){
alert(el.value);
}
change();
A fiddle is here.