Triggering events on input elements using javascript - javascript

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.

Related

How to get element from DOM and set onclick event?

I have this html element:
<table id="miniToolbar">
<tbody>
<tr><td>
<button id="btnStrView" type="button" onclick='parent.ExecuteCommand()' class="button_air-medium">
<img id="streetView" class="miniToolbarContant" src="../stdicons/streetview-icon.png"></button>
</td></tr>
<tbody>
</table>
as you can see inside button I have on click event:
onclick='parent.ExecuteCommand()'
And I have this JS function:
function isMenuItemMasked(item)
{
var funcId = '75';
var elem = document.getElementById('btnStrView');
return false;
}
as you can see inside function I have variable called funcId.
I need to put this funcId to the on click event:
onclick='parent.ExecuteCommand('75')'
After I fetch element and put it inside elem variable how do I put funcId as parameter to parent.ExecuteCommand()?
I think you want to set the function argument dynamically. Without using external libraries I would do as follows:
function runSubmit() {
var value = document.getElementById("text").value;
document.getElementById("run").addEventListener('click', function() {
func(value);
});
}
function func(value) {
console.log(value);
}
<input id="text" type="text">
<input type="submit" value="Setup Param" onclick="runSubmit()">
<input id="run" type="submit" value="Run with param">
How to use this: When you run the snippet, you will see a text input, a Setup Param button and a Run with param button. Insert something in the text input and click Setup Param. After, click on Run with param to see the effect
The input text contains the string that will be used as parameter for func(value). The update of #run button callback is triggered by the "Setup param", through the runSubmit() callback. This callback adds to the #run element a listener for the 'click' event, that runs a function with the parameter fixed when event occurs.
This is only a MCVE, you should adapt it to your case scenario.
Mh... Actually #jacob-goh gave you this exact solution in a comment while I wrote this...
you can use jquery to call you function from inside the function and pass your variable to that function.
function isMenuItemMasked(item)
{
var funcId = "75";
$(document).ready(function(){
$("#btnStrView").click(function(){
parent.ExecuteCommand(funcId);
});
});
}
function ExecuteCommand(your_var){
alert(your_var);
//your code
}

Disabled textbox change event

Short Explanation
I want to do something whenever disabled textbox value is changed
Detailed Explanation
I have a disabled text box which value is setting programitically I want to bind the change event of disabled textbox to fire some other function. This is what I tried but won't work.
$('#Rate').change(function() {
// alert("Change Event Called");
CalculateMedicine();
});
$('input[id$=Rate]').bind("change", function () {
CalculateMedicine();
});
This both thing don't work for me and the I don't like the idea to put a function CalculateMedicine() to all the place from which possibly Rate textbox is changing.So apart from this solution any help will be appreciated
assuming that your your input has disable class on on click or something else you check like this
if ($( "#input" ).hasClass( "disable" )) {
Your logics and codes here //
}
//Hope this would help
You can use triggerfor a change event:
<input type="text" disabled="disabled" name="fname" class="myTextBox" ><br>
<input type="button" name="submit" id="submit" value="Submit">
Javascript:
$(".myTextBox").change(function(){
console.log("yes i m working");
});
$("#submit").click("input", function() {
$(".myTextBox").val("New value").trigger("change");
});
Check Demo
It is possible if one redefines the value property of that input.
<html>
<head>
<script>
function Init(){
var tE = document.querySelector('input'); //Our input field.
//We redefine the value property for the input
tE._value = tE.value;
Object.defineProperty(tE, 'value', {
get: function(){return this._value},
set: function(v){
console.log(1, 'The value changed to ' + v)
this._value = v;
this.setAttribute('value', v) //We set the attribute for display and dom reasons
//Here we can trigger our code
}
})
}
function Test(){
//In one second we are going to change the value of the input
window.setTimeout(function(){
var tE = document.querySelector('input'); //Our input field.
tE.value = 'Changed!'
console.log(0, 'Changed the value for input to ' + tE.value)
}, 1000)
}
</script>
</head>
<body onload = 'Init(); Test();'>
<input type = 'text' disabled = 'true' value = 'Initial' />
</body>
</html>
https://jsfiddle.net/v9enoL0r/
The change event will not fire if you change the value programmatically
See https://stackoverflow.com/a/7878081/3052648
A not elegant possible solution:
function checkChanges(){
if(prevRate != $('#Rate').val()){
prevRate = $('#Rate').val();
alert('changed');
}
}
var prevRate;
$(document).ready(function(){
prevRate = $('#Rate').val();
setInterval(function(){
checkChanges();
} ,500);
});
You can fire change event by the following code from wherever you want to fire change event or any other event. The event will be fired either value changed or not. Just place the code after from where you are changing value programatically.
element.dispatchEvent(new Event('change'))
let input = document.querySelector("input");
input.addEventListener("change", () => alert("Change Event is Fired"));
input.value = "xyz";
input.dispatchEvent(new Event("change"));
<input type="text" disabled value="abc">

Add an attribute to html element with javascript on page load?

What I've tried:
function addAttribute(){
document.getElementById('myid')...
};
window.onload = addAttribute;
How can I add add the attribute to my element with id="myid" ?
document.getElementById('telheaderid').yourattribute = "your_value";
For instance
document.getElementById('telheaderid').value = "your_value";
Using jQuery:
$('#telheaderid').attr('value', 'your_value');
EDIT:
Focus is the event that fires up when an element get focused or for instance when we click on the textarea it highlights thats the time.
Using jQuery:
$('#telheaderid').focus(function() {
$(this).val('');
// run any code when the textarea get focused
});
Using plain javascript:
document.getElementById('telheaderid').addEventListener('focus', function() {
this.value = "";
});
Use this:
document.getElementById('telheaderid').setAttribute('class','YourAttribute')
The W3C standard way:
function functionAddAttribute(){
document.getElementById('telheaderid').setAttribute('attributeName', 'attributeValue');
};
window.onload = functionAddAttribute;
for IE:
function functionAddAttribute(){
document.getElementById('telheaderid').attributeName = 'attributeValue';
};
window.onload = functionAddAttribute;
Enjoy your code!

Javascript - Function to use onclick?

I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!

How do I pass local variable value from one function to another?

In my script I have 2 functions. First function references to a div element, creates a paragraph element inside div and appends some text to this paragraph element;
In my second function is triggered by onclick event attached to a link element. I want the text in the div to be changed to another text when clicking on the link. I do realize that there are 2 options how to achieve this:
1) declare global variables and use them in my second function;
2) pass the variable value from first function to the second function and manipulkate this value from the second function
But the question is how to do I correctly pass the variable value from first function to second function:
Here is the code:
<a href=''onclick='change();return false;'>Change</a>
<div id='box'></div>
Javascript:
window.onload= function createEl(){
var el = document.createElement('p');
var x = document.getElementById('box');
var text = 'text';
el.appendChild(document.createTextNode(text));
x.appendChild(el);
}
function change(){
x.innerHTML="other text";
}
in general you can write this:
function one(){
var var1 = "hello";
two(var1);
}
function two(x){
alert(x);
}
this will alert "hello".
For what you're doing, I would register my events through code to make it easier to pass a variable. We want to use an argument in the event handling function to pass the data to it.
window.onload = function()
{
// do your normal stuff with creating elements
var anc = document.getElementById('ID of your a element here');
if(anc.attachEvent)
{
//code for ancient IE
anc.attachEvent('onclick', function(){change(x);});
}
else if(anc.addEventListener)
{
//code for modern browsers
anc.addEventListener('click', function(){change(x);});
}
}
function change(elem)
{
elem.innerHTML='other text';
}
Do note that older versions of IE don't recognize addEventListener and use attachEvent instead, as seen in the above if block. Here's the documentation for addEventListener.

Categories