Reputation: 33
I don't understand why the "this-reference" in function foo is not set with #searchval, when called by load event ?
The function call of foo at the keyup event works but the call does not work at the load event cause this-reference is not set.
Example:
<body>
<form action="" method="post">
<input type="text" name="test" value="<?=$_POST['test']?>" id="searchval">
<select id="names" size="3">
<option value="1">WTF1</option>
<option value="2">WTF2</option>
<option value="3">WTF3</option>
</select>
<input type="submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
var names = $('#names option').clone();
function foo() {
//Change the code to $('$searchval').val(); make it work
var val = $(this).val();
$('#names').empty();
names.filter(function(idx, el) {
return val === '' || $(el).text().indexOf(val) >= 0;
}).appendTo('#names');
}
$('#searchval').bind('keyup', foo);
$('#searchval').load(foo());
});
</script>
</html>
Upvotes: 0
Views: 131
Reputation: 413709
You're setting up the handler with the return value from "foo", not the function itself.
It should be:
$('#searchval').load( foo );
When you pass foo()
, you're first invoking the function — that's what ( )
does. By passing just the function reference you get the effect you want.
edit — on top of that issue, as noted in a comment you're trying to set up a "load" handler for an element that'll never get such an event. What is it that you expect to cause that event? Perhaps "change" is what you want instead of "load".
edit again — if you just want to simulate having "foo" called as it is when a "keyup" event happens, you can do two things:
You can use "triggerHandler":
$('#searchval').triggerHandler('keyup');
You can use "call":
foo.call($('#searchval')[0]);
In both cases, of course, you won't get an "event" object that's like the one you get on a real event, but "foo" doesn't care about that anyway.
Upvotes: 4