Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Triggering events on input elements using 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/

Upvotes: 1

Views: 5093

Answers (4)

The Alpha
The Alpha

Reputation: 146269

function change(){
    var el=document.getElementById('myId');
    el.value="Something";
    changed(el);
}
function changed(el){
    alert(el.value);
}
change();

A fiddle is here.

Upvotes: 0

scrappedcola
scrappedcola

Reputation: 10572

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();
}

Upvotes: 1

Nemoy
Nemoy

Reputation: 3427

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();"

Upvotes: 1

Rob W
Rob W

Reputation: 349262

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 <a href="javascript:alert('test');">Test</a>.

Upvotes: 2

Related Questions