Event for .val() filled form fields

I have the following code


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {  
	$("input[id='test']").keyup(function() {
		$('#test_output').val('My Message');
	});
	
	$("input[id='test_output']").live('change', function() {
		$('#test2_output').val('My Message 2');
	});
});
</script>

</head>

<body>
<input type="text" name="test" id="test"/> 
<input type="text" id="test_output" /> 
<input type="text" id="test2_output" />
</body>
</html>

Basically, when I type something in “test”, I want “My Message” to appear in “test_output”. This is working. I also would like to fill “My Message 2” in “test2_ouput” whenever “test_output” is filled using the .val();, this is not working, even though I am using .live().

How can I solve this?

Thank you

So you’ve found that jQuery’s .val() method doesn’t trigger a change event.

You can either trigger it manually, or you can add a wrapper to the .val() method so that it automatically triggers the change event.

Here’s the first solution. You don’t need to use the live method, that’s only for when you require an element that’s added to a page to have an event.

I’ve also simplified the selectors in this example to just the identifiers.


$(function() {  
	$('#test').keyup(function () {
		$('#test_output').val('My Message').trigger('change');
	});
	
	$('#test_output').change(function () {
		$('#test2_output').val('My Message 2');
	});
});

The other way where you take over the .val method, is a bit more complex but can help to simplify the rest of your code.


$(function() {  
    $.fn._val = $.fn.val;
    $.fn.val = function () {
        var obj = $.fn._val.apply(this, arguments);
        if (arguments.length > 0) {
            obj.trigger('change');
        }
        return obj;
    }

    $('#test').keyup(function () {
        $('#test_output').val('My Message');
    });
    $('#test_output').change(function () {
        $('#test2_output').val('My Message 2');
    });
});