tags:

views:

37

answers:

5

Hello,

For each enter or for every entry into the text box I want the alert to be triggered

<input type="text" id="val_xml" class="val_xml1" maxlength="3" size="2"/>


$('#val_xml').bind('change',function() {
    var v = $('#val_xml').val();
    alert(v);
});

Thanks Jean

A: 
$('#val_xml').bind('change keyup',function() {
    var v = $(this).val();
    alert(v);
});
Arnaud F.
Your code will not work. `$this` is undefined. You probably meant `$(this)`, but `this.value` is the most efficient.
Peter Ajtai
Doh ! Thanks for reply, didn't see it, was to fast...
Arnaud F.
+2  A: 

Your code seems to work.

Make sure to include a doc ready / Script tags, etc. And if you want an automatic alert once the maximum number of characters are entered:

​$(function() {
    $('#val_xml').bind('change',function() {            
        alert(this.value);

        // These alerts can get annoying. If you are done with it, unbind it:
        // $(this).unbind(arguments[0]); // <== would unbind this alert
     });

      // Check if max chars entered at each keyup
    $(document).keyup(function() {
        var $valXML = $("#val_xml");
        if ($valXML.val().length >= $valXML.attr("maxlength") )
            $valXML.trigger("change");
    });
});​

Try it out with this jsFiddle


The above does one alert for each "entry". This means that the alert is triggered by blurring, by pressing enter, or when 3 chars (the max) are entered.

Note that each time you write $('#val_xml') you create a new jQuery object. So in your code, you create the exact same jQuery object twice. Additionally, there's no need to use a jQuery method to access the value property of a DOM element, which is why I use this.value.

References:
.attr()
.keyup()
.trigger()

Peter Ajtai
A: 

http://api.jquery.com/keyup/ and .focus() if you want "each enter or for every entry"

Tudorizer
A: 

For text boxes, the change event is only fired when the element loses focus. If you want this function to execute each time a new character is added, bind to the keypress event instead of change.

keydown and keyup could also be used, but please note that these will only fire once, even if the user holds down the key so that multiple characters are added. keypress will fire once for each added character.

Colin O'Dell
Like @Peter mentioned above, this would be very dysfunctional, but my answer assumes you want this function fired for every keypress for some reason and that the alert() call is just for testing purposes.
Colin O'Dell
A: 

use the keyup event.

$('#val_xml').keyup(function() {
    var v = $('#val_xml').val();
    alert(v);
});
Brian Flanagan